21. Merge Two Sorted Lists
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.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
题目链接:https://leetcode.com/problems/merge-two-sorted-lists/
思路一
哨兵节点指向l1,让l2不断插进来。
/**
* 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;
if(l2==NULL) return l1;
ListNode* node = new ListNode(0);
node->next = l1;
ListNode* pre = node;
while(l2!=NULL && l1!=NULL){
if(l2->val < l1->val){
pre->next = l2;
l2 = l2->next;
pre->next->next = l1;
pre = pre->next;
}else{
pre = pre->next;
l1 = l1->next;
}
}
if(l2!=NULL){
pre->next = l2;
}
return node->next;
}
};
思路二
哨兵节点作为一个新的list,l1和l2中较小的放进新list。
/**
* 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;
if(l2==NULL) return l1;
ListNode* node = new ListNode(0);
node->next = NULL;
ListNode* pre = node;
while(l2!=NULL && l1!=NULL){
if(l2->val < l1->val){
pre->next = l2;
l2 = l2->next;
}else{
pre->next = l1;
l1 = l1->next;
}
pre = pre->next;
}
if(l1!=NULL){
pre->next = l1;
}
if(l2!=NULL){
pre->next = l2;
}
return node->next;
}
};



被折叠的 条评论
为什么被折叠?



