单链表的基本操作:
1.建立结点。
2.删除结点。
3.排序。
4.遍历。
代码如下:
1 #include<iostream> 2 using namespace std; 3 #ifndef LIST 4 #define LIST 5 typedef char DataType; 6 struct Node 7 { 8 DataType A; 9 Node *Next; 10 }; 11 class List 12 { 13 Node *Head; 14 public: 15 List(){Head=NULL;} 16 void CreatNode(); 17 void Remove(); 18 void Sort(); 19 void Print()const; 20 }; 21 void List::CreatNode() 22 { 23 Node *p; 24 p=new Node; 25 cin>>p->A; 26 p->Next=Head; 27 Head=p; 28 if(p->A=='0') 29 return; 30 else 31 CreatNode(); 32 return; 33 } 34 void List::Remove() 35 { 36 DataType ch; 37 if(Head==NULL) 38 { 39 cout<<"sorry,The list don't have any data\n";return; 40 } 41 cout<<"please cin the Data of needing remove"<<endl; 42 cin>>ch; 43 Node *p,*q; 44 //排除头指针的情况 45 while(Head->A==ch) 46 { 47 p=Head; 48 Head=Head->Next; 49 delete p; 50 if(Head==NULL) 51 return; 52 } 53 //除头指针的情况 54 q=Head; 55 p=q->Next; 56 int i=0; 57 while(p!=NULL) 58 { 59 if(p->A==ch) 60 { 61 q->Next=p->Next; 62 delete p; 63 cout<<"delete the ---"<<i<<"---data......"<<endl; 64 } 65 q=q->Next; 66 p=p->Next; 67 } 68 return; 69 } 70 void List::Sort() //默认升序 71 { 72 Node *p,*q,*item; 73 if(Head==NULL) 74 { 75 cout<<"sorry,The list don't have any data\n";return; 76 } 77 p=Head; 78 q=Head->Next; 79 while(q!=NULL) 80 { 81 if(p==Head&&p->A > q->A) 82 { 83 p->Next=q->Next; 84 q->Next=p; 85 Head=q; 86 p=Head; 87 q=Head->Next; 88 } 89 else if(p->A > q->A) 90 { 91 item->Next=q; 92 p->Next=q->Next; 93 q->Next=p; 94 95 p=item->Next; 96 q=p->Next; 97 98 } 99 item=p; 100 p=p->Next; 101 q=q->Next; 102 } 103 cout<<"Sort OK!\n"; 104 return; 105 } 106 void List::Print()const 107 { 108 Node *p; 109 p=Head; 110 while(p!=NULL) 111 { 112 cout<<p->A<<' '; 113 p=p->Next; 114 } 115 return ; 116 } 117 #endif 118 int main() 119 { 120 121 List L; 122 123 L.CreatNode(); 124 L.Sort(); 125 L.Print(); 126 return 0; 127 }
-------剑指天涯-------
浙公网安备 33010602011771号