C++实现单链表的建立/测长/打印/删除/插入/排序/转置等操作
#include <iostream> using namespace std; struct student { int data; student *next; }node; //(1)单链表的建立 student *create() { //student node; student *head,*p,*s; int x; char c; head=new student; p=head; cout<<"please input the datas:"<<endl; while(cin>>x) { s=new student; s->data=x; //cout<<s->data<<endl; p->next=s; p=s; cin.get(c); if(c==' ') break; } p->next=NULL; head=head->next;//去掉哑节点 return head; } //(2)链表的测长 int length(student *node) { student *p=node; int n=0; while(p!=NULL) { n++; p=p->next; } return n; } //(3)链表的打印 void print_list(student *node) { student *p=node; while(p!=NULL) { cout<<p->data<<endl; p=p->next; } } //(4)单链表删除节点 student *del_node(student *head,int num) { student *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; delete p1; } else { p2->next=p1->next; //delete p1; } } else cout<<"could not find number "<<num<<endl; return head; } //(5)单链表插入节点 student *insert_node(student *head,int num) { student *p0,*p1,*p2;//p0是带插入节点 p1=head; p0=new student; p0->data=num; while(p0->data>p1->data && p1->next!=NULL) { p2=p1;p1=p1->next; } if(p0->data<=p1->data) { if(p1==head) { p0->next=p1; head=p0; } else { p2->next=p0; p0->next=p1; } } else { p1->next=p0; p0->next=NULL; } return head; } //(6)实现单链表的排序 student *sort_list(student *head) { int N=length(head); student *p1,*p2,*t; int temp; p1=head; for(int i=1;i<N;i++) { p2=p1->next; for(int j=i+1;j<=N;j++) { if(p1->data>p2->data) { temp=p1->data; p1->data=p2->data; p2->data=temp; } p2=p2->next; } //if(i==1) head=p1; p1=p1->next; } return head; } //(7)实现单链表的转置 student *reverse_list(student *head) { student *p1,*p2,*p3; p1=head; p2=p1->next; while(p2) { p3=p2->next; p2->next=p1; p1=p2; p2=p3; } head->next=NULL; head=p1; return head; } //(8)删除链表头结点 student *remove_head(student *head) { student *p; p=head; head=p->next; delete p; return head; } int main() { student *p=create(); int N=length(p); cout<<"length of list"<<N<<endl; cout<<"Print list"<<endl; print_list(p); //student *p2=del_node(p,3); //print_list(p2); //student *p3=insert_node(p2,2); //print_list(p3); //student *p4=sort_list(p); //print_list(p4); //student *p5=reverse_list(p); //print_list(p5); student *p6=remove_head(p); print_list(p6); return 0; }