// list.cpp : 定義控制檯應用程序的入口點。 // #include "stdafx.h" #include<iostream> #include<stdio.h> #include<string.h> #include<conio.h> using namespace std; struct ListNode { int data; ListNode *next; }; //創建單鏈表 ListNode *creat() { ListNode *head,*p,*s; int x,cycle=1; head=(ListNode*)malloc(sizeof(ListNode)); p=head; cout<<"請輸入單鏈表的數據,以0做爲結束標識:"<<endl; while(cycle) { cin>>x; if(x!=0)//以0爲標識 { s=(ListNode *)malloc(sizeof(ListNode)); s->data=x; p->next=s; p=s; } else cycle=0; } head=head->next; p->next=NULL; cout<<endl; return (head); } //求單鏈表的長度 int length(ListNode *head) { int n=0; ListNode *p; p=head; while(p!=NULL) { p=p->next; n++; } return(n); } //輸出單鏈表 void print(ListNode *head) { ListNode *p;int n; n=length(head); cout<<"如今,長度爲"<<n<<"的單鏈表更新爲:"<<endl; p=head; if(head!=NULL) { while(p!=NULL) { cout<<p->data<<'\t'; p=p->next; } } printf("\n"); } //刪除單鏈表中的某個元素 ListNode *del(ListNode *head,int num) { ListNode *p1,*p2; p1=head; while(num!=p1->data&&p1->next!=NULL) { p2=p1; p1=p1->next; } if(num==p1->data) { if(p1==head) { head=p1->next; free(p1); } else p2->next=p1->next; } else cout<<num<<"沒有在單鏈表中找到!"<<endl;//printf("\n%d 沒有在單鏈表中找到!",num); return head; } //在單鏈表中插入一個元素 ListNode *insert(ListNode *head,int num) { ListNode *p0,*p1,*p2; p1=head; p0=(ListNode *)malloc(sizeof(ListNode)); p0->data=num; while(p0->data>p1->data&&p1->next!=NULL) { p2=p1;p1=p1->next; } if(p0->data<=p1->data) { if(head==p1) { p0->next=p1; head=p0; } else { p2->next=p0; p0->next=p1; } } else { p1->next=p0; p0->next=NULL; } return head; } //對單鏈表從小到大排序: ListNode *sort(ListNode *head) { ListNode *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; } //對單鏈表進行逆置 ListNode *reverse(ListNode *head) { ListNode *p1,*p2,*p3; if(head==NULL||head->next==NULL) return head; p1=head,p2=p1->next; while(p2) { p3=p2->next; p2->next=p1; p1=p2; p2=p3; } head->next=NULL; head=p1; return head; } int main() { ListNode *head; int n,del_num,insert_num; head=creat(); print(head); cout<<"\n請對單鏈表排序:"; head=sort(head); print(head); cout<<"\n請輸入單鏈表中要刪除的數據: "; cin>>del_num; head=del(head,del_num); print(head); cout<<"\n請輸入單鏈表中要插入的數據:"; cin>>insert_num; head=insert(head,insert_num); print(head); cout<<"\n請對單鏈表進行逆置:"; head=reverse(head); print(head); system("pause"); return 0; }