虛擬頭結點的作用是:簡化插入/刪除邏輯+方便返回頭節點+減少邊界錯誤
Leetcode206鏈表反轉
206. 反轉鏈表 - 力扣(LeetCode)
頭插法
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):def reverseList(self, head):""":type head: Optional[ListNode]:rtype: Optional[ListNode]"""#定義current,dumpyheaddumpyhead=ListNode(-1)dumpyhead.next=None#因為希望當前節點指向的next是dumpy的nextcurrent=headwhile current!=None:tmp=current.next#記憶當前結點下一節點是什么current.next=dumpyhead.nextdumpyhead.next=currentcurrent=tmpreturn dumpyhead.next
Leetcode6刪除鏈表的倒數第N個結點
19. 刪除鏈表的倒數第 N 個結點 - 力扣(LeetCode)
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):def removeNthFromEnd(self, head, n):""":type head: Optional[ListNode]:type n: int:rtype: Optional[ListNode]"""#不能先初始化在head,否則因為n+1可能超出# slow=head# fast=headdummynode=ListNode(-1,head)slow=dummynodefast=dummynodefor i in range(n+1):fast=fast.nextwhile(fast):fast=fast.nextslow=slow.nextslow.next=slow.next.nextreturn dummynode.next