Leetcode Merge Two Sorted Lists
2013-10-13 13:11
295 查看
将两个有序(默认是升序)的链表合并,由于要返回head结点,所以一开始要增加一个dummy(虚拟的)结点,即cur一开始new出来的。
如果head结点为空的话,设置head结点为cur->next。
如果head结点为空的话,设置head结点为cur->next。
/** * 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) { // Note: The Solution object is instantiated only once and is reused by each test case. if(l1 == NULL) return l2; if(l2 == NULL) return l1; ListNode *head = NULL, *cur = new ListNode(1); while(l1 != NULL || l2 != NULL){ if(l1 == NULL || (l1 != NULL && l2 != NULL && l2->val <= l1->val)){ cur->next = new ListNode(l2->val); l2 = l2->next; } else if(l2 == NULL || (l1 != NULL && l2 != NULL && l2->val > l1->val)){ cur->next = new ListNode(l1->val); l1 = l1->next; } if(head == NULL) head = cur->next; cur = cur->next; } return head; } };
相关文章推荐
- leetcode 日经贴,Cpp code -Merge Two Sorted Lists
- LeetCode 21. Merge Two Sorted Lists(合并两个有序单链表)
- 【Leetcode】【Easy】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 2.9 难度系数2
- LeetCode - 21. Merge Two Sorted Lists
- LeetCode-Merge Two Sorted Lists
- LeetCode Merge Two Sorted Lists
- LeetCode_merge-two-sorted-lists
- Leetcode: Merge Two Sorted Lists
- 开始刷leetcode day10:Merge Two Sorted Lists
- 【C++】【LeetCode】21. Merge Two Sorted Lists
- Leetcode: Merge Two Sorted Lists
- Merge Two Sorted Lists(LeetCode)
- Leetcode:merge_two_sorted_lists
- leetcode: Merge Two Sorted Lists
- Leetcode 21. Merge Two Sorted Lists
- Python学习——leetcode(Merge Two Sorted Lists )