leetcode合并有序链表
合并有序链表
题目链接:![https://leetcode.cn/problems/merge-two-sorted-lists/]
有两种方法求解该题目:
- 非递归方法
- 递归方法
非递归方法
使用非递归方法,关键在于记录已经合并好的链表的尾指针。
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {if (list1 == nullptr)return list2;else if (list2 == nullptr)return list1;ListNode* p = list1;ListNode* q = list2;ListNode* head; //已经合并好的链表的表头ListNode* r = new ListNode(); //已经合并好的链表的表尾head = r;while (p && q){if (p->val < q->val){r->next = p;p = p->next;}else{r->next = q;q = q->next;}r = r->next;}if (p == nullptr)r->next = q;elser->next = p;return head->next;
}
这里使用了哨兵节点,用于统一头部数据的比较,这使我们不需要对两个链表的头节点进行特殊处理,可以直接在循环中处理。
递归方法
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {if(l1==NULL)return l2;if(l2==NULL)return l1;if(l1->val < l2->val){l1->next = mergeTwoLists(l1->next,l2);return l1;}else{l2->next = mergeTwoLists(l1,l2->next);return l2;}
}
