//文件LinList.h
#ifndef LINLIST2_H_INCLUDED
#define LINLIST2_H_INCLUDED
#include<iostream>
using namespace std;
template<class T>class LinList;
template<class T>
class ListNode
{
friend class LinList<T>;
private:
ListNode<T>*next;
T data;
public:
ListNode(ListNode<T>*ptrNext=NULL)
{
next=ptrNext;
}
ListNode(const T&item,ListNode<T>*ptrNext=NULL)
{
data=item;
next=ptrNext;
}
~ListNode(void){}
};
template<class T>
class LinList
{
private:
ListNode<T>*head;
int size;
ListNode<T>*Index(int i);
public:
LinList(void);
~LinList(void);
int Size(void)const;
void Insert(const T&item,int i);
T Delete(int i);
T GetData(int i);
};
template<class T>
LinList<T>::LinList()
{
head=new ListNode<T>();
size=0;
}
template<class T>
LinList<T>::~LinList(void)
{
ListNode<T>*p,*q;
p=head;
while(p!=NULL)
{
q=p;
p=p->next;
delete q;
}
size=0;
head=NULL;
}
template<class T>
ListNode<T>*LinList<T>::Index(int i)
{
if(i<1||i>size-1)
{
cout<<"参数i越界出错!"<<endl;
exit(0);
}
if(i==-1)return head;
ListNode<T>*p=head->next;
int j=0;
while(p!=NULL&&j<i)
{
p=p->next;
j++;
}
return p;
}
template<class T>
int LinList<T>::Size(void)const
{
return size;
}
template<class T>
void LinList<T>::Insert(const T&item,int i)
{
if(i<0||i>size)
{
cout<<"参数i越界出错!"<<endl;
exit(0);
}
ListNode<T>*p=Index(i-1);
ListNode<T>*q=new ListNode<T>(item,p->next);
p->next=q;
size++;
}
template<class T>
T LinList<T>::Delete(int i)
{
if(size==0)
{
cout<<"链表已空无元素可删"<<endl;
exit(0);
}
if(i<0||i>size-1)
{
cout<<"参数i越界出错!"<<endl;
exit(0);
}
ListNode<T>*s,*p=Index(i-1);
s=p->next;
p->next=p->next->next;
T x=s->data;
delete s;
size--;
return x;
}
template<class T>
T LinList<T>::GetData(int i)
{
if(i<0||i>size-1)
{
cout<<"参数i越界出错!"<<endl;
exit(0);
}
ListNode<T>*p=Index(i);
return p->data;
}
#endif // LINLIST2_H_INCLUDED
//主程序
#include<iostream>
#include<stdlib.h>
#include"LinList2.h"
main(void)
{
LinList<int>myList;
int s[]={1,2,3,4,5,6,7,8,9,10},n=10;
int temp;
for(int i=0;i<n;i++)
myList.Insert(s[i],i);
myList.Delete(4);
for(int i=0;i<myList.Size();i++)
{
temp=myList.GetData(i);
cout<<temp<<" ";
}
}