復習一下單鏈表的常用操作,包括單鏈表的創建、插入、刪除、排序、逆置以及打印輸出等。
#include<IOSTREAM> using namespace std; typedef struct Single_link { int data; struct Single_link *next; }node; //單鏈表的創建 node *Create() { node *head,*p,*s; int x,cycle=1; head=(node *)malloc(sizeof(node)); p=head; cout<<"Input the elements of the link:"<<endl; while (cycle) { cin>>x; if (x!=0) { s=(node *)malloc(sizeof(node)); s->data=x; p->next=s; p=s; } else cycle=0; } head=head->next; p->next=NULL; return head; } //單鏈表測長 int length(node *head) { node *p; p=head; int count=0; while (p!=NULL) { p=p->next; count++; } return count; } //////////////////////////////////單鏈表插入/////////////////////////////////////// node *Insert(node *head,int element) { //p是遍歷指針,q用於保存插入節點的位置節點,s是將要插入的節點 node *p,*q,*s; p=head; //創建插入的新節點 s=(node *)malloc(sizeof(node)); s->data=element; while (s->data>p->data && p->next!=NULL) { q=p; p=p->next; } if (s->data<=p->data) { if (head==p) { s->next=p; head=s; } else { q->next=s; s->next=p; } } else { p->next=s; s->next=NULL; } return head; } /////////////////////////////單鏈表刪除///////////////////////////////////////////// node *del(node *head,int element) { //p是遍歷指針,q用於保存刪除的位置節點 node *p,*q; p=head; while (p->data!=element && p->next!=NULL) { q=p; p=p->next; } if (p->data==element) { if (head==p) { head=p->next; free(p); } else { q->next=p->next; } } else { cout<<" Not find the delete element."<<endl; } return head; } ///////////////////////////////單鏈表逆序/////////////////////////////////////////// node *Reverse(node *head) { node *p,*q,*s; if (head==NULL && head->next==NULL) { return head; } p=head; q=p->next; while (q) { s=q->next; q->next=p; p=q; q=s; } head->next=NULL; head=p; return head; } ///////////////////////////////單鏈表排序/////////////////////////////////////////// node *Sort(node *head) { node *p; int n; int temp; n=length(head); if(head==NULL && head->next==NULL) { return head; } p=head; for (int j=1;j<n;j++) { p=head; for (int i=0;i<n-j;i++) { if (p->data > p->next->data) { temp=p->data; p->data=p->next->data; p->next->data=temp; } p=p->next; } } return head; } ////////////////////////打印單鏈表/////////////////////////////////////////////////////////// void print(node *head) { node *p; p=head; int n=length(head); cout<<"鏈表中共有"<<n<<"記錄."<<endl; if (head!=NULL) { cout<<"鏈表中元素為:"<<endl; while (p!=NULL) { cout<<p->data<<" "; p=p->next; } cout<<endl; } } int main() { node *head; int n; head=Create(); print(head); head=Sort(head); print(head); cout<<"Input the insert number:"<<endl; cin>>n; Insert(head,n); print(head); cout<<"Input the delete number:"<<endl; cin>>n; del(head,n); print(head); head=Reverse(head); print(head); return 0; }