设计一个函数 void merge(List La, List Lb) , 其功能是将Lb合并到La中,其中La和Lb的元素均为非递减有序排列,且合并后的La的元素也为非递减有序排列。
//非递减有序排列即关键字递增序排列,但是并非单调递增(因为有重复的关键字)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| #include <stdio.h> #include <stdlib.h>
typedef struct T_Node { int d; struct T_Node* next; } Node, * List;
void merge(List La, List Lb) { Node* pre, * p, * q; pre = La; p = La->next; q = Lb->next; while (p && q) { if (p->d < q->d) { pre->next = p; pre = p; p = p->next; } else { pre->next = q; pre = q; q = q->next; } } if (p) pre->next = p; else pre->next = q; free(Lb); }
void main() { List La, Lb; Node* p, * q; int i;
La = (List)malloc(sizeof(Node)); p = La; Lb = (List)malloc(sizeof(Node)); q = Lb;
for (i = 1; i <= 10; i++) { p->next = (Node*)malloc(sizeof(Node)); p->next->d = 2 * i; p->next->next = NULL; p = p->next;
q->next = (Node*)malloc(sizeof(Node)); q->next->d = 3 * i - 2; q->next->next = NULL; q = q->next; } merge(La, Lb); p = La->next; while (p != NULL) { printf(" %d ", p->d); p = p->next; } printf("\n"); }
|