和大神们学习每天一题(leetcode)-Merge Two Sorted Lists
2014-12-08 15:37
183 查看
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.
two lists.
class Solution { public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { if (l2 == NULL) return l1; if (l1 == NULL) { l1 = l2; return l1; } ListNode * LNpL1 = l1, *LNpL2 = l2, *LNpFor = NULL;//指针1和2分别指向两个链表的头 while (LNpL1 != NULL&&LNpL2 != NULL)//遍历两个链表知道其中一个完全遍历 { if (LNpL1->val < LNpL2->val)//比较当前指针指向节点的值,指针1的值如果小于2的值则指针1向后移动 { LNpFor = LNpL1; LNpL1 = LNpL1->next; } else//否则将指针2指向的结点插入到指针1指向结点的前面 { if (LNpFor == NULL) { LNpFor = LNpL2; l1 = LNpFor; } else { LNpFor->next = LNpL2; LNpFor = LNpFor->next; } LNpL2 = LNpL2->next; LNpFor->next = LNpL1; } } if (LNpL1 == NULL)//如果链表1遍历完全,则将链表2剩余结点接在链表1后面 { LNpFor->next = LNpL2; } return l1; } };
相关文章推荐
- 和大神们学习每天一题(leetcode)-Intersection of Two Linked Lists
- LeetCode 学习 LinkedList 专项(4)—— Merge Two Sorted Lists
- Python学习——leetcode(Merge Two Sorted Lists )
- LeetCode编程练习 - Merge Two Sorted Lists学习心得
- 和大神们学习每天一题(leetcode)-Merge Sorted Array
- leetcode 30: 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, Solution
- [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