合并两个链表
Easy; LinkedList;
Last updated
Easy; LinkedList;
Last updated
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
#
# two pointers methods:
# idea:
# 1. two pointers pointing to the head of two list, and create a fake head
# used as the previous node of head of merge list
# use one pointer to iterate the new list
# 2. loop until one of two pointers is None,
# each time extract and add the smaller node to the next of the end of new list
# 3. when one of pointers is none, append the remaining unchecked list to the end of new list
# return new list
pt1, pt2 = l1, l2
fake_head = ListNode(None)
cur = fake_head
while pt1 and pt2:
# extract node with smaller value to the end of merged list
if pt1.val < pt2.val:
cur.next = pt1
pt1 = pt1.next
else:
cur.next = pt2
pt2 = pt2.next
# move forward
cur = cur.next
# append the remaining list
if pt1:
cur.next = pt1
if pt2:
cur.next = pt2
return fake_head.next