Linux C++ 单链表添加,删除,输出,逆序操作

/*单链表操作*/
#include <iostream>
using namespace std; class Node{ public: Node(){ next=0; } Node(int el, Node *ptr=0) { info=el; next=ptr; } int info; Node *next; }; class LList{ public: LList(){head=tail=0;} ~LList(); int isEmpty(){return head==0;} void addToHead(int); void addToTail(int); int deleteHead(); int deleteTail(); void deleteNode(int); bool isInList(int)const; void displayall() const; void inverted(); private: Node *head, *tail; }; LList::~LList(){ for(Node *p;!isEmpty();){ p=p->next; delete head; head=p; } } void LList::addToHead(int el){ head=new Node(el,head); if(tail==0) tail=head; } void LList::addToTail(int el){ if(tail!=0){ tail->next=new Node(el); tail=tail->next; } else head=tail=new Node(el); } int LList::deleteHead(){ int el=head->info; Node *tmp=head; if(head==tail) head=tail=0; else head=head->next; delete tmp; return el; } int LList::deleteTail(){ int el=tail->info; if(head==tail) { delete tail; head=tail=0; } else{ Node *tmp=NULL; for(tmp=head;tmp->next!=tail;tmp=tmp->next); delete tail; tail=tmp; tail->next=0; } return el; } void LList::deleteNode(int el){ if(head!=0){ if(head==tail && el == head->info) { delete head; head=tail=0; } else if(el ==head->info) { Node *tmp=head; head=head->next; delete tmp; } else{ Node *pred,*tmp; for(pred=head,tmp=head->next;tmp!=0 && (tmp->info==el);pred=pred->next,tmp=tmp->next); if(tmp!=0){ pred->next=tmp->next; if(tmp==tail) tail=pred; delete tmp; } }     } } bool LList::isInList(int el) const{ Node *tmp; for(tmp=head;tmp!=0 && !(tmp->info==el);tmp=tmp->next); return tmp!=0; } void LList::displayall() const{     Node *tmp; for(tmp=head;tmp!=0;tmp=tmp->next) {cout<<tmp->info<<"-";} cout<<endl; } void LList::inverted(){ Node *pre=NULL; Node *next=NULL; tail=head; while(head!=NULL) { next=head->next; head->next=pre; pre=head; head=next; } head=pre; } int main() { LList *list= new LList(); list->addToTail(1); list->addToTail(2); list->addToTail(3); list->addToTail(4); list->addToHead(0); list->addToTail(4); list->addToTail(5); list->addToTail(6); list->addToTail(7); list->addToTail(8); list->displayall(); list->inverted(); list->displayall(); return 0; }

输出结果:

0-1-2-3-4-4-5-6-7-8-
8-7-6-5-4-4-3-2-1-0-

  

  

猜你喜欢

转载自www.cnblogs.com/mingyue605/p/10192737.html