#include<iostream>#include<cstdlib> using namespace std; //定义链表节点; typedef struct Node{ int data; Node*next; }node; //创建链表; node*Create_list() { node *head; node*p; node*s; int x; head=(node*)malloc(sizeof(node)); p=head; int temp=1;cout<<"please enter the data,(entre '0' to end ):";
while(temp) { cin>>x; if(0!=x){ s=(node*)malloc(sizeof(node)); s->data=x; p->next=s; p=s;} else temp=0; } head=head->next; p->next=NULL; return head;}int length_list(node*head)//链表长度;{ int n=0; node*p=head; while(p!=NULL) { p=p->next; ++n;} return n;}void print_list(node*head)//打印链表;{ node*p; if(NULL==head) cout<<"this is null list !"; else p=head; while(NULL!=p) {cout<<p->data<<"\t"; p=p->next;} cout<<endl;}node*sort_list(node*head) //链表排序;{ node*p; int temp; int n=length_list(head); if(NULL==head||head->next==NULL) return head; else 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;}node*reverse_list(node*head) //链表逆置;{ node*p1,*p2,*p3; while((NULL==head)||(NULL==head->next)) return head; p1=head; p2=p1->next; p1->next=NULL; while(NULL!=p2) { p3=p2->next; p2->next=p1; p1=p2; p2=p3; } return p1;}//删除链表头元素;node*delete_headelement(node*head){ node*p=head; if(NULL==p||NULL==p->next) return NULL; else head=head->next; free(p); return head;}//提供一个单链表,不知道元素个数,只遍历一次,求中间元素;int middle_ele_list(node*head){ node*p1,*p2; p1=head; p2=head; while((p2->next!=NULL)&&(p2->next->next!=NULL)) { p2=p2->next->next; p1=p1->next; } return p1->data;}//求链表倒数第m个元素;int backwords_list(node*head,int m){ node*p=reverse_list(head); //先逆置链表; for(int i=1;i<m;++i) p=p->next; return p->data;}node*Merge_list(node*a,node*b) //将两个有序(升序)的链表连接后,仍然有序;{ node*head=NULL; node*temp=NULL; if(a==NULL) return b; else if(b==NULL) return a; if(a->data>b->data) { head=b;b=b->next;} else { head=a;a=a->next;} temp=head; while((a!=NULL)&&(b!=NULL)) { if((a->data)>(b->data)) { temp->next=b; temp=b; b=b->next; } else if(a->data<=b->data) { temp->next=a; temp=a; a=a->next; } } if(a==NULL) while(b!=NULL) { temp->next=b; temp=b; b=b->next; } else while(a!=NULL) { temp->next=a; temp=a; a=a->next; } temp->next=NULL; return head;}node*RecurrenceMerge(node*a,node*b)//递归 合并两个升序的链表,合并后仍有序;{ if(a==NULL) return b; else if(b==NULL) return a; node*head=NULL; if(a->data>b->data) { head=b; head->next=RecurrenceMerge(a,b->next); } else { head=a; head->next=RecurrenceMerge(b,a->next); } return head;}
单链表的创建、排序、逆置等
最新推荐文章于 2021-02-16 08:15:21 发布