LeetCode—Merge Two Sorted Lists融合两个有序单链表
2015-04-15 16:02
351 查看
首先两个单链表是有序的
在融合两个单链表的时候,如果想到的是在一个序列上进行增减,那么会非常麻烦
这里一定要单独开一个序列头进行存储,不一定需要开辟内存,主要是一个概念
其实方法感觉和归并算法的merge都是一个概念
提供剑指offer上的递归的解决办法
在融合两个单链表的时候,如果想到的是在一个序列上进行增减,那么会非常麻烦
这里一定要单独开一个序列头进行存储,不一定需要开辟内存,主要是一个概念
其实方法感觉和归并算法的merge都是一个概念
/** * 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) { if(l1 == NULL) { return l2; } else if(l2 == NULL) { return l1; } ListNode *head = NULL; if(l1->val < l2->val) { head = l1; l1 = l1->next; } else { head = l2; l2 = l2->next; } ListNode *phead = head; while(l1 && l2) { if(l1->val < l2->val) { head->next = l1; head = head->next; l1 = l1->next; } else { head->next = l2; head = head->next; l2 = l2->next; } } if(l1) { head->next = l1; } if(l2) { head->next = l2; } return phead; } };
提供剑指offer上的递归的解决办法
/** * 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) { if(l1 == NULL) { return l2; } else if(l2 == NULL) { return l1; } ListNode *head = NULL; if(l1->val < l2->val) { head = l1; head->next = mergeTwoLists(l1->next,l2); } else { head = l2; head->next = mergeTwoLists(l1,l2->next); } return head; } };
相关文章推荐
- Leetcode:Merge Two Sorted Lists 合并两个有序单链表
- [LeetCode]Sort List 链表排序 + Merge Two Sorted List 合并两个有序链表
- LeetCode 21. Merge Two Sorted Lists(合并两个有序单链表)
- LeetCode 刷题: 合并两个有序链表 (merge two sorted list)
- [LeetCode]Merge Two Sorted Lists & Remove Duplicates from Sorted List 两个有序链表合并为一个&删除链表重复元素
- LeetCode-21 Merge Two Sorted Lists(合并两个有序链表)
- Leetcode Merge Two Sorted Lists(合并两个有序表)
- LeetCode--Merge Two Sorted Lists(合并两个有序链表)Python
- leetcode:Merge Two Sorted Lists (链接两个有序链表)【面试算法题】
- [LeetCode-21] Merge Two Sorted Lists(合并两个有序链表)
- 【LeetCode刷题】排列两个有序链表Merge Two Sorted Lists(递归思想)(java)
- Merge Two Sorted Lists 合并两个有序链表@LeetCode
- LeetCode-Merge Two Sorted Lists--链接两个有序链表
- LeetCode 21 Merge Two Sorted Lists (有序两个链表整合)
- 面试题17:合并两个有序链表(Leetcode-21:Merge Two Sorted Lists)
- [LeetCode 21]Merge Two Sorted Lists 合并两个有序链表
- 21-Merge Two Sorted Lists-合并两个有序单链表
- [LeetCode21]Merge Two Sorted Lists(合并两个有序链表)
- LeetCode 21. Merge Two Sorted Lists (合并两个有序链表)
- Leetcode Merge Two Sorted Lists 合并两个有序链表