[LeetCode] 055: Merge Two Sorted Lists
来源:互联网 发布:好看的网络自制剧 编辑:程序博客网 时间:2024/05/18 02:16
[Problem]
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.
[Solution]
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.
[Solution]
/**说明:版权所有,转载请注明出处。Coder007的博客
* 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
// at least one of them is NULL
if(NULL == l1)return l2;
if(NULL == l2)return l1;
// both of them are not NULL
ListNode *head = NULL;
if(l1->val < l2->val){
head = new ListNode(l1->val);
l1 = l1->next;
}
else{
head = new ListNode(l2->val);
l2 = l2->next;
}
// merge
ListNode *p = head;
while(l1 != NULL || l2 != NULL){
if(NULL == l1){
p->next = new ListNode(l2->val);
l2 = l2->next;
}
else if(NULL == l2){
p->next = new ListNode(l1->val);
l1 = l1->next;
}
else if(l1->val < l2->val){
p->next = new ListNode(l1->val);
l1 = l1->next;
}
else{
p->next = new ListNode(l2->val);
l2 = l2->next;
}
p = p->next;
}
return head;
}
};
阅读全文
0 0
- [LeetCode] 055: 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] 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] 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】Merge Two Sorted Lists
- Leetcode: Merge Two Sorted Lists
- 【LeetCode】Merge Two Sorted Lists
- [LeetCode] 051: Median of Two Sorted Arrays
- JavaSE学习之一,坚持!
- [LeetCode] 052: Merge Intervals
- [LeetCode] 053: Merge K Sorted Lists
- [LeetCode] 054: Merge Sorted Array
- [LeetCode] 055: Merge Two Sorted Lists
- 大逃亡
- Ajax和Servlet做项目时遇到的问题
- [LeetCode] 056: Minimum Depth of Binary Tree
- LeetCode题目:3. Longest Substring Without Repeating Characters
- &与&&的区别
- [LeetCode] 057: Minimum Path Sum
- [LeetCode] 058: Minimum Window Substring
- [LeetCode] 059: Multiply Strings