LeetCode | Merge Two Sorted Lists(合并两个链表)
2014-08-18 16:42
507 查看
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.
题目解析:
合并链表,很简单,注意好传入为空指针即可。
由于头结点的确定,为了避免在循环中做无谓的比较,直接在while之前先确定头指针。
the nodes of the first two lists.
题目解析:
合并链表,很简单,注意好传入为空指针即可。
由于头结点的确定,为了避免在循环中做无谓的比较,直接在while之前先确定头指针。
class Solution { public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { if(l1 == NULL) return l2; if(l2 == NULL) return l1; ListNode *head; if(l1->val < l2->val){ head = l1; l1 = l1->next; }else{ head = l2; l2 = l2->next; } ListNode *p = head; while(l1 && l2){ if(l1->val < l2->val){ p->next = l1; p = l1; l1 = l1->next; }else{ p->next = l2; p = l2; l2 = l2->next; } } if(l1 == NULL){ p->next = l2; } if(l2 == NULL) p->next = l1; return head; } };
相关文章推荐
- [LeetCode] Merge Two Sorted Lists 合并两个有序链表
- [LeetCode]Merge Two Sorted Lists & Remove Duplicates from Sorted List 两个有序链表合并为一个&删除链表重复元素
- LeetCode 21 Merge Two Sorted Lists(合并两个已排序的链表)(Linked List)
- leetcode Merge Two Sorted Lists 合并两个有序链表
- 【LeetCode-面试算法经典-Java实现】【021-Merge Two Sorted Lists(合并两个排好序的单链表)】
- LeetCode--Merge Two Sorted Lists(合并两个有序链表)Python
- [LeetCode 21]Merge Two Sorted Lists 合并两个有序链表
- Leetcode Merge Two Sorted Lists 合并两个有序链表
- [LeetCode21]Merge Two Sorted Lists(合并两个有序链表)
- [LeetCode-21] Merge Two Sorted Lists(合并两个有序链表)
- leetcode 21. Merge Two Sorted Lists(C语言,合并两个排序的链表为一个排序链表)32
- LeetCodet题解--21. Merge Two Sorted Lists(合并两个排序好的链表)
- 面试题17:合并两个有序链表(Leetcode-21:Merge Two Sorted Lists)
- LeetCode-21- Merge Two Sorted Lists(合并两个已排序链表)
- LeetCode 21. Merge Two Sorted Lists (合并两个有序链表)
- [LeetCode] 21. Merge Two Sorted Lists 合并两个有序链表 @python
- 两个升序链表的合并 Merge Two Sorted Lists 【 leetcode】
- LeetCode Merge Two Sorted Lists(合并两个有序链表)
- LeetCode-21 Merge Two Sorted Lists(合并两个有序链表)
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode