連結串列的插入 刪除 排序 倒敘
阿新 • • 發佈:2018-12-27
#include <iostream> using namespace std; #include <stdio.h> #include <stdexcept> #include <conio.h> #include <string.h> #include <stack> struct Node { int data; struct Node *next; }; Node *Creat() { Node *head,*p,*s; head=(Node *)malloc(sizeof(Node)); p=head; int n; while(scanf("%d",&n)&&n) { s=(Node *)malloc(sizeof(Node)); s->data=n; p->next=s; p=s; } head=head->next; p->next=NULL; return head; } int Length(Node *head) { Node *p; p=head; int len=0; while(NULL!=p) { p=p->next; ++len; } return len; } Node *Del(Node *&head,int num) { Node *p1,*p2; p1=head; while (num!=p1->data&&NULL!=p1->next) { p2=p1; p1=p1->next; } if (num==p1->data) { if(p1==head) { head=p1->next; free(p1); } else { p2->next=p1->next; } } else { printf("%d cound not be found\n",num); } return head; } //插入頭結點時,這是頭結點改變了,所以這裡要注意 就是所謂的引用與指標的區別 //函式體內 要修改一個變數的值該怎麼做呢???不懂的自己百度 //這種情況老是容易忘記,請仔細注意了 Node *Insert(Node *&head,int num) { Node *p0,*p1,*p2; p1=head; p0=(Node*)malloc(sizeof(Node)); p0->data=num; while (num>p1->data&&NULL!=p1->next) { p2=p1; p1=p1->next; } if (num<=p1->data) { if (head==p1) { p0->next=head; head=p0; } else { p2->next=p0; p0->next=p1; } } else { p1->next=p0; p1->next->next=NULL; } return head; } Node *Sorted(Node *head)//簡單的氣泡排序法 { Node *p1,*p2; p1=head; p2=head; int len=Length(head); if (NULL==head||NULL==head->next) return head; for (int i=0; i<len; ++i) { p2=p1; for (int j=i+1; j<len; ++j) { if(p1->data>p2->next->data) { p1->data^=p2->next->data; p2->next->data^=p1->data; p1->data^=p2->next->data; } p2=p2->next; } p1=p1->next; } return head; } Node *Reverse(Node *&head) { Node *p1,*p2,*p3; p1=head; if (NULL==head||NULL==head->next) { return head; } p2=p1->next; while (p2) { p3=p2->next; p2->next=p1; p1=p2; p2=p3; } head->next=NULL; head=p1; return head; } void Print(Node *head) { Node *p; p=head; while (NULL!=p) { printf("%d ",p->data); p=p->next; } printf("\n"); }
#include "list.h" int main() { Node *head; int del_num,insert_num; head=Creat(); Print(head); cout<<"\n\n"; cout<<"連結串列的長度: "<<Length(head)<<"\n\n"; cin>>del_num; Del(head,del_num); cout<<"刪除後的連結串列: "; Print(head); while(cin>>insert_num&&insert_num) { cout<<"插入後的連結串列: "; Insert(head,insert_num); Print(head); } Reverse(head); cout<<"倒序輸出:"; Print(head); Sorted(head); cout<<"排序後的連結串列: "; Print(head); system("pause"); return 0; }