(链表)Leetcode206链表反转+Leetcode6删除链表的倒数第N个结点+虚拟头节点使用

发布于:2025-08-31 ⋅ 阅读:(26) ⋅ 点赞:(0)

虚拟头结点的作用是:简化插入/删除逻辑+方便返回头节点+减少边界错误

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,dumpyhead
        dumpyhead=ListNode(-1)
        dumpyhead.next=None#因为希望当前节点指向的next是dumpy的next
        current=head
        while current!=None:
            tmp=current.next#记忆当前结点下一节点是什么
            current.next=dumpyhead.next
            dumpyhead.next=current
            current=tmp
        return 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=head
        dummynode=ListNode(-1,head)
        slow=dummynode
        fast=dummynode
        for i in range(n+1):
            fast=fast.next
        while(fast):
            fast=fast.next
            slow=slow.next
        slow.next=slow.next.next
        return dummynode.next


网站公告

今日签到

点亮在社区的每一天
去签到