[LeetCode] Merge Two Sorted Lists
2013-01-27 20:49
357 查看
/** * 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) { // Start typing your C/C++ solution below // DO NOT write int main() function if (!l1) return l2; if (!l2) return l1; ListNode *head = NULL; if (l1->val < l2->val) { head = l1; l1 = l1->next; } else { head = l2; l2 = l2->next; } ListNode *node = head; while (l1 && l2) { if (l1->val < l2->val) { node->next = l1; node = l1; l1 = l1->next; } else { node->next = l2; node = l2; l2 = l2->next; } } if (l1) node->next = l1; if (l2) node->next = l2; return head; } };
Small Case: 4ms
Large Case: 60ms
Time: O(n)
Space: O(1)
相关文章推荐
- LeetCode_Linked List_Merge Two Sorted Lists
- LeetCode 21 Merge Two Sorted Lists(合并两个已排序的链表)(Linked List)
- LeetCode-21-Merge-Two-Sorted-Lists 递归水题
- leetcode Merge Two Sorted Lists
- LeetCode_Merge Two Sorted Lists
- 【LeetCode】Merge Two Sorted Lists
- leetcode解题方案--021--Merge Two Sorted Lists
- LeetCode_21_Merge Two Sorted Lists
- # 蜗牛慢慢爬 LeetCode 21. Merge Two Sorted Lists [Difficulty: Easy]
- leetcode 21 Merge Two Sorted Lists
- leetcode 21:Merge Two Sorted Lists(15-10-9)
- leetcode21 Merge Two Sorted Lists
- LeetCode Merge Two Sorted Lists
- leetcode-Merge Two Sorted Lists
- 编程题2- Merge Two Sorted Lists(leetcode-21)
- [leetcode]Merge Two Sorted Lists
- LeetCode Merge Two Sorted Lists
- LeetCode 21: Merge Two Sorted Lists
- leetcode:21 Merge Two Sorted Lists-每日编程第十七题
- LeetCode之Merge Two Sorted Lists