【leetcode】合并两个有序链表
问题描述:
将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
解法一
临时头结点的使用(复习)。
同步比较两个链表的头的大小,进行新链表的构建。
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
res = ListNode(None)
node = res
while l1 and l2:
if l1.val<l2.val:
node.next,l1 = l1,l1.next
else:
node.next,l2 = l2,l2.next
node = node.next
if l1:
node.next = l1
else:
node.next = l2
return res.next
同方法c++版本
/**
* 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 (!l2)
return l1;
if (!l1)
return l2;
ListNode st= ListNode(0);
ListNode *ptr=&st;
while(l1 && l2){
if (l1->val<l2->val){
ptr->next=l1;
l1=l1->next;
}
else{
ptr->next=l2;
l2=l2->next;
}
ptr = ptr->next;
}
if (!l1)
ptr->next=l2;
if(!l2)
ptr->next=l1;
return st.next;
}
};
解法二
把所有的节点拿出来排序。然后在制成做成新的链表。
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1 and not l2:
return []
tmp = []
while l1 and l2:
tmp.append(l1.val)
l1 = l1.next
tmp.append(l2.val)
l2 = l2.next
if l1:
while l1 :
tmp.append(l1.val)
l1 = l1.next
if l2:
while l2 :
tmp.append(l2.val)
l2 = l2.next
tmp.sort()
head = ListNode(tmp.pop(0))
start = head
while tmp:
ttmp = ListNode(tmp.pop(0))
head.next = ttmp
head = ttmp
return start
解法三:
C++递归:
/**
* 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;
if(l1->val < l2->val){
l1->next = mergeTwoLists(l1->next,l2);
return l1;
}else{
l2->next = mergeTwoLists(l1,l2->next);
return l2;
}
}
};