单链表相关操作

来源:互联网 发布:mac有必要安装office 编辑:程序博客网 时间:2024/05/20 16:00

这是自己写的最长的一次代码了 在机房敲了一天。。。 以前一直用list来水链表的题 这次终于体会到痛苦了

#include <cstdio>#include <iostream>#include <cstdlib>#include <cstring>#include <algorithm>#include <vector>using namespace std;typedef struct node //单链表{int date;node *next;}*S,list;void create_list1(S head,int n) //顺序建立含n个元素的单链表(需要一个移动指针){S p,t;p=head;while(n--){t=new list;cin>>t->date;t->next=NULL;p->next=t;p=t;}}void create_list2(S head,int n) //逆序建立一个含n个元素的单链表(不需要移动指针){S t;while(n--){t=new list;cin>>t->date;t->next=head->next;head->next=t;}}void output_list(S head)//输出链表{S p=head->next;while(p!=NULL){if(p->next!=NULL)cout<<p->date<<" ";elsecout<<p->date<<endl;    p=p->next;}}bool find_list(S head,int x)//查找{S p=head->next;while(p!=NULL)   {if(p->date==x)return 1;p=p->next;   }return 0;}S reseve_list(S head) //链表逆置{S pre,cur,nex;if(head->next==NULL||head->next->next==NULL) return head;//检测边界pre=head->next;cur=pre->next;nex=NULL;while(cur!=NULL){nex=cur->next;cur->next=pre;pre=cur;cur=nex;}head->next->next=NULL;//设置尾链表head->next=pre;//调整链表头return head;}S merge_list(S head1,S head2) //两个有序单链表合并 返回一个新的头指针(的前指针){S p;p=NULL;if(head1==NULL&&head2==NULL)return p;else if(head1==NULL&&head2!=NULL)return head2;else if(head1!=NULL&&head2==NULL)return head1;else{if(head1->date<=head2->date){p=head1;p->next=merge_list(head1->next,head2);}else{p=head2;p->next=merge_list(head1,head2->next);}return p;}}S get_end_list(S head)//获得链表的尾指针{S p=head;while(p->next!=NULL)p=p->next;return p;}void sort_list(S head,S last)//快速排序{if(head==NULL||last==NULL) return ;if(head==last) return ;S slow=head,fast=head->next,t=head;while(fast&&fast!=last->next){if(fast->date<=head->date){t=slow;slow=slow->next;swap(slow->date,fast->date);}fast=fast->next;}swap(head->date,slow->date);sort_list(head,t);sort_list(slow->next,last);}void delete_node(S head,int m)//删除节点{S p=head;if(head->next==NULL) return ;while(p->next!=NULL){if(p->next->date==m)p->next=p->next->next;elsep=p->next;}}void apart_list(S head,S head1,S head2)//链表拆分(此为奇偶拆分){S t,q,t1=head1,t2=head2;S p=head->next;while(p!=NULL){if(p->date%2==0){t=new list;t->date=p->date;t->next=NULL;t1->next=t;t1=t;}else{q=new list;q->date=p->date;q->next=NULL;t2->next=q;t2=q;}    p=p->next;}}void delete_same_list(S head)//删除重复元素{S p=head->next,t;while(p!=NULL){t=p;while(t->next!=NULL){if(p->date==t->next->date)t->next=t->next->next;elset=t->next;}p=p->next;}}int lenth_list(S head)//计算链表长度{int cnt=0;S p=head->next;while(p!=NULL){cnt++;p=p->next;}return cnt;}int main(){int n;while(cin>>n)  {S head=new list;head->next=NULL;head->date=-1;create_list1(head,n);delete_same_list(head);sort_list(head,get_end_list(head));output_list(head);  }return 0;}


0 0