Last Updated: 2023-10-30 12:13:09 Monday
-- TOC --
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
题目要求了要通过splicing两个list来得到新的list,即不能够创建新的节点。
Example 1:
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:
Input: list1 = [], list2 = []
Output: []
Example 3:
Input: list1 = [], list2 = [0]
Output: [0]
Constraints:
- The number of nodes in both lists is in the range [0, 50]. 输入有可能为空。
- -100 <= Node.val <= 100
- Both list1 and list2 are sorted in non-decreasing order. 两个输入list,均为non-decreasing order。
singly-linked list概念很简单,带代码处理起来最麻烦,因为它只有一个next指针。此题还有双指针推进的因数。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
if not list1:
return list2
if not list2:
return list1
if list1.val < list2.val:
head = p = list1
p1 = list1.next
p2 = list2
else:
head = p = list2
p1 = list1
p2 = list2.next
while p1!=None and p2!=None:
if p1.val < p2.val:
p.next = p = p1
p1 = p1.next
else:
p.next = p = p2
p2 = p2.next
if p1 == None:
p.next = p2
else:
p.next = p1
return head
=
没有返回值,连续的=
从最左边开始。/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) noexcept{
if(!list1)
return list2;
if(!list2)
return list1;
ListNode *head, *p;
if(list1->val < list2->val){
head = p = list1;
list1 = list1->next;
} else {
head = p = list2;
list2 = list2->next;
}
while(list1 && list2){
if(list1->val < list2->val){
p = p->next = list1;
list1 = list1->next;
} else {
p = p->next = list2;
list2 = list2->next;
}
}
if(!list1)
p->next = list2;
else
p->next = list1;
return head;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
if(!list1)
return list2;
if(!list2)
return list1;
struct ListNode *head, *p;
if(list1->val < list2->val){
head = p = list1;
list1 = list1->next;
} else {
head = p = list2;
list2 = list2->next;
}
while(list1 && list2){
if(list1->val < list2->val){
p = p->next = list1;
list1 = list1->next;
} else {
p = p->next = list2;
list2 = list2->next;
}
}
if(!list1)
p->next = list2;
else
p->next = list1;
return head;
}
本文链接:https://cs.pynote.net/ag/leetcode/202310211/
-- EOF --
-- MORE --