无表头结点的有序环形链表的合并

来源:互联网 发布:淘宝里卖家中心在哪里 编辑:程序博客网 时间:2024/05/03 07:55

//数据结构教程 蔡子经版 第一章课后习题16

//这题真是bt,想了很多方法发现没有一个比较方便,无奈只得把环形链表变成单向链表,最后再把单向链表转换成环形

//求大神指教简便方法

#include<stdio.h>#include<stdlib.h>struct node {   int num;     struct node* next; };typedef struct node Node;Node* create(int n){int i;Node*head,*p,*q;if(n==0)return NULL;head=(Node*)malloc(sizeof(Node));p=head;for(i=1;i<n;i++){scanf("%d",&p->num);q=(Node*)malloc(sizeof(Node));p->next=q;p=q;}scanf("%d",&p->num);p->next=head;return head;}Node* insert(Node* head,Node *ps)//单向链表的插入操作{Node *p1=head,*p2;if(head==NULL)head=ps;else{while (ps->num>p1->num && p1->next){p2=p1;p1=p1->next;}if(ps->num<=p1->num){if(head==p1) head=ps; else p2->next=ps;ps->next=p1;}else { p1->next=ps;ps->next=NULL; }}return head;}Node *merge(Node *ah,Node *bh){Node *head=NULL,*p,*pa=ah,*pb=bh,*ch;if(ah==NULL && bh==NULL)return NULL;if(ah==NULL && bh!=NULL){while(pb->next!=bh)pb=pb->next;pb->next=NULL;pb=bh;head=insert(head,pb);}if(ah!=NULL && bh!=NULL){while(pa->next!=ah)//将环形链表A变为单向链表pa=pa->next;pa->next=NULL;while(pb->next!=bh)//将环形链表B变为单向链表pb=pb->next;pb->next=NULL;pa=ah;pb=bh;head=insert(head,pa);while(pb){p=pb;pb=pb->next;head=insert(head,p);}}if(ah!=NULL && bh==NULL){while(pa->next!=ah)pa=pa->next;pa->next=NULL;pa=ah;head=insert(head,pa);}ch=head;while(ch->next)//将单向链表改成环形链表ch=ch->next;ch->next=head;ch=ch->next;return ch;}void print(Node *a){Node *p=a;if(a==NULL){printf("NULL\n");return ;}printf("%d ",a->num);while(a->next!=p){a=a->next;printf("%d ",a->num);}printf("\n");}int main(){int m,n;while(scanf("%d%d",&m,&n)!=EOF){Node *ah,*bh,*ch;ah=create(m);bh=create(n);ch=merge(ah,bh);print(ch);}return 0;}

原创粉丝点击