链表的建立与归并
程序代码:
#include<iostream> #include<stdlib.h> #define len sizeof(list) using namespace std; struct list { int num; struct list *next; }; list *creat(int n); list *merger(list *head1, list *head2); void delnode(list *head); int main() { list *LA, *LB,*LC; LA = creat(1); LB = creat(2); LC = merger(LA, LB); while (LC != NULL) { cout << LC->num<<"\t"; LC = LC->next; } delnode(LC); return 0; } list *creat(int n) { list *p1, *p2,*head; int i{1}; while (i <= 5) { p1 = (list *)malloc(len); if (i == 1) { head = p1; p1->num = n; } else { p2->next = p1; p1->num = p2->num + 2; } p2 = p1; i++; } p2->next = NULL; return head; } list *merger(list *p1, list *p2) { list *head, *p; while (p1 != NULL || p2 != NULL) { int i{ 1 }; if (p1->num > p2->num) { if (i == 1) { p = head = p2; p2 = p2->next; } else { p->next = p2; p = p2; p2 = p2->next; } } else { if (i == 1) { p = head = p1; p1 = p1->next; } else { p->next = p1; p = p1; p1 = p1->next; } } if (p1 = NULL) { p->next= p2; } if (p2 = NULL) { p->next= p1; } i++; } return head; } void delnode(list *head) { if (head = NULL) return; list *t, *p; p = head; if (p != NULL) { t = p; p = p->next; free(t); } head = NULL; }
为什么merger没有起作用
[此贴子已经被作者于2017-11-14 22:13编辑过]