链表合并~
程序代码:
#include<stdio.h> #include<malloc.h> typedef struct LNode { int data; struct LNode *next; }LNode,*Linklist; Linklist la,lb, l; Linklist creat(int n){ Linklist head, node, end; head = (Linklist)malloc(sizeof(LNode)); head->next=NULL; end = head; printf("请输入%d个数",n); for (int i = 0; i < n; i++) { node = (Linklist )malloc(sizeof(LNode)); scanf("%d", &node->data); end->next = node; end = node; } end->next=NULL; return head; } void print() { Linklist p; p=l->next; while(p) { printf("%d ",p->data); p=p->next; } } Linklist mergelist() { Linklist pa,pb,pc,head; pa=la->next; pb=lb->next; l=la; l->next=NULL; if(pa->data<pb->data) { pc=pa; pa=pa->next; } else { pc=pb; pb=pb->next; } while(pa&&pb) { if(pa->data<=pb->data) { pa->next=pc; pc=pa; pa=pa->next; } else { pb->next=pc; pc=pb; pb=pb->next; } } if(pa=NULL) { while(pb!=NULL) { pb->next=pc; pc=pb; pb=pb->next; } pb->next=NULL; l->next=pc; } else { while(pb!=NULL) { pa->next=pc; pc=pa; pa=pa->next; } pa->next=NULL; l->next=pc; } return l; } int main() { la=creat(4); lb=creat(4); l=mergelist(); print(); return 0; }
可以输入两个链表的数据,但没办法输出合并后的数据,相知道错在哪?