[LeetCode]80. Merge Two Sorted Lists合并两个排序链表
2015-11-15 10:33
260 查看
原文链接:https://www.geek-share.com/detail/2658554780.html
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.
Subscribe to see which companies asked this question
解法1:递归。首先比较头节点大小,若l2->val>l1->val,则返回mergeTwoLists(l2,l1);否则(1)如果l1->next!=NULL,则比较l1->next->val与l2->val的大小,这样可以确定前两个元素的顺序,
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if (l1 == NULL) return l2; if (l2 == NULL) return l1; if (l1->val <= l2->val) { if (l1->next != NULL && l1->next->val <= l2->val){ ListNode* node = mergeTwoLists(l1->next->next, l2); l1->next->next = node; } else if (l1->next != NULL && l1->next->val > l2->val) { ListNode* node = mergeTwoLists(l1->next, l2->next); l2->next = node; l1->next = l2; } else l1->next = l2; return l1; } else return mergeTwoLists(l2, l1); } };
解法2:迭代。新建一个指针help,然后遍历l1和l2,将二者中较小的链接到help后面。最后返回help的下一个节点作为头节点。注意两个链表可能长度不一样,要将长链表最后剩下的元素链接到新链表中。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if (l1 == NULL) return l2; if (l2 == NULL) return l1; ListNode* help = new ListNode(0); ListNode* head = help; while (l1 != NULL && l2 != NULL) { if (l1->val <= l2->val) { help->next = l1; l1 = l1->next; } else { help->next = l2; l2 = l2->next; } help = help->next; } if (l1 != NULL) help->next = l1; if (l2 != NULL) help->next = l2; return head->next; } };
转载于:https://www.cnblogs.com/aprilcheny/p/4964996.html
相关文章推荐
- [LeetCode]80. Merge Two Sorted Lists合并两个排序链表
- Leetcode 21 Merge Two Sorted Lists 将两个已排序的链表合并起来
- LeetCodet题解--21. Merge Two Sorted Lists(合并两个排序好的链表)
- leetcode 21. Merge Two Sorted Lists(C语言,合并两个排序的链表为一个排序链表)32
- LeetCode-21- Merge Two Sorted Lists(合并两个已排序链表)
- LeetCode 21 Merge Two Sorted Lists(合并两个已排序的链表)(Linked List)
- LeetCode-21 Merge Two Sorted Lists(合并两个有序链表)
- lintcode 容易题 :Merge Two Sorted Lists合并两个排序链表
- leetcode merge-two-sorted-lists 合并两个有序链表
- LeetCode 21. Merge Two Sorted Lists (合并两个有序链表)
- leetcode 21. Merge Two Sorted Lists 两个单向链表合并 指针与解指针
- [LeetCode 21]Merge Two Sorted Lists 合并两个有序链表
- [leetcode]Merge Two Sorted Lists合并两个有序链表
- LeetCode-Merge k Sorted Lists-合并k个排序链表-自底向上归并排序+链表操作
- LeetCode Merge Two Sorted Lists(合并两个有序链表)
- [leetcode]Merge Two Sorted Lists合并两个有序链表2
- Leetcode Merge Two Sorted Lists 合并两个有序链表
- 【LeetCode-面试算法经典-Java实现】【021-Merge Two Sorted Lists(合并两个排好序的单链表)】
- Merge Two Sorted Lists 合并两个有序链表@LeetCode
- 两个升序链表的合并 Merge Two Sorted Lists 【 leetcode】