(链表)Leetcode206链表反转+Leetcode6删除链表的倒数第N个结点+虚拟头节点使用
虚拟头结点的作用是:简化插入/删除逻辑+方便返回头节点+减少边界错误
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