LeetCode之21----Merge Two Sorted Lists
题目:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the
nodes of the first two lists.
题目大意:
给定两个有序的链表,求有序合并后的链表。
思路:
链表有序合并也是数据结构里边的经典题目了。大体思路就是分别扫描两个链表,比较两个节点的大小值,把较小的节点值尾插到结果链表屁股后边,然后再次扫描两个链表,直到其中某一个链表或者两条链表同时结束。如果是某条链表提前结束则应将另一条链表的其余节点都接到结果链表上。
代码:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { ListNode *result = new ListNode(0); ListNode *p1 = l1; ListNode *p2 = l2, *tail = result; while (p1 && p2) { if (p1->val <= p2->val) { tail->next = p1; p1 = p1->next; } else { tail->next = p2; p2 = p2->next; } tail = tail->next; } if (p1) { tail->next = p1; p1 = p1->next; } if (p2) { tail->next = p2; p2 = p2->next; } tail = result; result = tail->next; delete(tail); return result; }看一个比较简洁的递归版吧。
递归版:
class Solution { public: ListNode* mergeTwoLists(ListNode* l1, 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; } } };