链表的哨兵节点作用:遍历到结尾的时候不需要反转链表回到初始节点。
就是拿一个变量存一下虚拟头节点。
最后返回这个虚拟头节点的next就是答案。
这里用了两个变量:pre_head和cur。cur用来遍历,pre_head用来记住起始节点。
# 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]:
# 链表的遍历一般都是while循环
pre_head = ListNode()
cur = pre_head
while list1 or list2:
if not list1:
list1val = 100
list2val = list2.val
elif not list2:
list2val = 100
list1val = list1.val
else:
list1val = list1.val
list2val = list2.val
if list1val > list2val:
cur.next = list2
list2 = list2.next
else:
cur.next = list1
list1 = list1.next
cur = cur.next
return pre_head.next