- #include <iostream>
- using namespace std;
- template <class T>
- class list;
- template <class T>
- class Node
- {
- T data;
- Node *next;
- public:
- Node()
- {
- next=NULL;
- }
- ~Node()
- {}
- friend class list<T>;
- };
- template <class T>
- class list
- {
- Node<T> *head;
- public:
- list()
- {
- head=new Node<T>;
- }
- ~list()
- {
- Node<T> *p,*q;
- p=head;
- while (p->next!=NULL)
- {
- q=p->next;
- delete p;
- p=q;
- }
- delete p;
- }
- int length()const
- {
- int count=0;
- Node<T> *p;
- p=head->next;
- while (p->next!=NULL)
- {
- count++;
- p=p->next;
- }
- count++;
- return count;
- }
- bool empty()const
- {
- return (head->next==NULL);
- }
- void display()const
- {
- Node<T> *p;
- p=head->next;
- while(p->next!=NULL)
- {
- cout<<p->data<<endl;
- p=p->next;
- }
- cout<<p->data<<endl;
- }
- bool getelem(int i,T &e)const
- {
- int count=1;
- Node<T> *p;
- p=head->next;
- while (count<i)
- {
- p=p->next;
- count++;
- }
- e=p->data;
- return 1;
- }
- int getlocation(T e)const
- {
- int count=1;
- Node<T> *p;
- p=head->next;
- while (p->data!=e)
- {
- p=p->next;
- count++;
- }
- return count;
- }
- bool insert(int i,T e)
- {
- int count=1;
- Node<T> *p,*q;
- p=head;
- while (count<i)
- {
- p=p->next;
- count++;
- }
- q=p->next;
- Node<T> *t=new Node<T>;
- t->data=e;
- p->next=t;
- t->next=q;
- return 1;
- }
- bool deletes(int i,T &e)
- {
- int count=1;
- Node<T> *p,*q;
- p=head;
- while (count<i)
- {
- p=p->next;
- count++;
- }
- q=p->next;
- e=q->data;
- p->next=q->next;
- delete q;
- return 1;
- }
- bool setelem(int i,T e)
- {
- int count=1;
- Node <T>*p;
- p=head;
- while (count<=i)
- {
- p=p->next;
- count++;
- }
- p->data=e;
- return 1;
- }
- };
- int main()
- {
- list<char> L;
- L.insert(1,'a');
- L.insert(2,'b');
- L.insert(3,'d');
- L.display();
- L.insert(3,'c');
- L.display();
- char t;
- L.deletes(3,t);
- cout<<t<<endl;
- L.display();
- L.getelem(3,t);
- cout<<t<<endl;
- L.setelem(3,'c');
- L.display();
- cout<<L.length()<<endl;
- cout<<L.empty()<<endl;
- cout<<L.getlocation('c')<<endl;
- system ("pause");
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/250420149364.html
来源: http://www.codesnippet.cn/detail/250420149364.html