/*问题描述:A和B是两个单链表(带头结点) 其中元素递增有序,设计一个算法,将A,B归并成一个按元素值非递减有序的链表CC由A,B中的结点构成 */ #include#include typedef struct LNode{ int data; struct LNode* next;}LNode,*LinkList; //头插法构建单链表(输出时与创建顺序相反) void init1(LinkList &L){ //一定要给L动态开辟空间,并且让 L->next = NULL; L = (LinkList)malloc(sizeof(LinkList)); L->next = NULL; LinkList s; int x; scanf("%d",&x); while(x!=-1){ s = (LinkList)malloc(sizeof(LinkList)); s->data = x; s->next = L->next; L->next = s; scanf("%d",&x); }} //尾插法构建单链表void init2(LinkList &L){ L = (LinkList)malloc(sizeof(LinkList)); L->next = NULL; LinkList s,r; r = L; int x; scanf("%d",&x); while(x!=-1){ s = (LinkList)malloc(sizeof(LinkList)); s->data = x; r->next = s; r = s; scanf("%d",&x); } s->next = NULL;}void merge(LinkList a,LinkList b,LinkList &c){ LinkList p,q,s,r; p = a->next; q = b->next; c = (LinkList)malloc(sizeof(LinkList)); c->next = NULL; r = c; while(p!=NULL&&q!=NULL){ s = (LinkList)malloc(sizeof(LinkList)); if(p->data data){ s->data = p->data; printf("=========%d\n",s->data ); r->next = s; r = s; //只动一个指针,切记 p = p->next; }else{ s->data = q->data; printf("++++++++++%d\n",s->data ); r->next = s; r = s; //只动一个指针,切记 q = q->next; } } if(p!=NULL){ s = (LinkList)malloc(sizeof(LinkList)); s->data = p->data; r->next = s; r = s; //只动一个指针,切记 p = p->next; }else{ s = (LinkList)malloc(sizeof(LinkList)); s->data = q->data; r->next = s; r = s; //只动一个指针,切记 q = q->next; } r->next=NULL;} //输出链表中的元素void show(LinkList L){ LinkList p = L->next; while(p){ printf("%d ",p->data); p = p->next; }} int main(){// LinkList L;//// //头插法测试 //// init1(L);//// //尾插法插法测试 //// init2(L);// // show(L); LinkList a,b,c; printf("请输入链表a的元素:"); init2(a); printf("\n"); printf("请输入链表b的元素:"); init2(b); printf("\n"); merge(a,b,c); show(c); return 0;}