链表类的设计

mac2025-04-01  5

/*链表类的设计: (1)向链表中插入元素,主要包括向链表头插入元素和向链表尾插入元素 (2)从链表中删除元素,主要看、包括删去链表头的元素和删去链表尾的元素 */ #include<iostream> using namespace std; class link { friend class list; link *next; int x; public: link():x(0) { } link(int a):x(a) { } void disp() { cout<<"x="<<x<<endl; } }; class list { link *first; link *last; public: list() { first=last=new link; } ~list() { Clear(); delete first; } void Insert(link s) { link *p=first; first=new link; *first=s.x; first->next=p; } void Append(link s) { link *p=last; last=new link; *p=s.x; p->next=last; } void Delete() { if(first==last); else { link *p=first->next; delete first; first=p; } } void Remove() { if(first==last); else if(first->next==last) Delete(); else { link *p=first,*q; while(p!=last) { q=p; p=p->next; } delete p; q->next=last; } } void Clear() { link *p=first,*q; while(p!=last) { q=p->next; delete p; p=q; } first=last; } void disp() { link *p=first; while(p!=last) { p->disp(); p=p->next; } } }; int main() { list x; x.Insert(link(1)); x.Insert(link(2)); x.Append(link(3)); x.Insert(link(4)); x.disp(); }

最新回复(0)