题目
已知两个有序链表,试合并这两个链表,使得合并后的链表仍然有序(注:这两个链表没有公共结点,即不交叉)。
分析
既然两个链表都是有序的,所以合并它们跟合并两个有序数组没有多少区别,只是链表操作涉及到指针,不能大意。
方法一:非递归方法
使用2个指针list1和list2分别遍历两个链表,将较小值结点归并到结果链表中。如果有一个链表归并结束后另一个链表还有结点,则把另一个链表剩下部分加入到结果链表的尾部。代码如下所示:
- struct node *sorted_merge(struct node *a, struct node *b) {
- struct node result; //使用一个结点用于保存结果
- struct node *tail = &result;
- if (a == NULL) return b; //特殊情况处理
- else if (b == NULL) return a;
- while (a && b) {
- if (a->data <= b->data) { //a链表结点值小,加入到链表尾部,并更新tail,遍历a链表下一个结点
- tail->next = a;
- tail = a;
- a = a->next;
- } else { //b链表结点值小,加入到链表尾部,更新tail,遍历b链表下一个结点
- tail->next = b;
- tail = b;
- b = b->next;
- }
- }
- if (a) //a结点未遍历完,则加入到尾部
- tail->next = a;
- if (b) //b结点未遍历完,加入到尾部
- tail->next = b;
- return result.next;
- }
- struct node* sorted_merge_recur(struct node* a, struct node* b)
- {
- struct node* result = NULL;
- //基础情况
- if (a==NULL) return(b);
- else if (b==NULL) return(a);
- // 递归遍历
- if (a->data <= b->data) {
- result = a;
- result->next = sorted_merge_recur(a->next, b);
- }
- else {
- result = b;
- result->next = sorted_merge_recur(a, b->next);
- }
- return(result);
- }