leetcode Python 19. 删除链表的倒数第N个节点(中等、链表)

给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.

说明:给定的 n 保证是有效的。

思路:给定两个指针,首先一个先走n步,然后两个再一起走,直到最早的那个到达终点。其中,有两种情况,一个是删除第一个,改变头结点;一个不是删除第一个,不用改变头结点。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        pre=head
        end=head
        for _ in range(n):
            end=end.next
        if not end:
            return head.next
        while end.next:
            pre=pre.next
            end=end.next
        pre.next=pre.next.next
        return head
        

执行用时: 52 ms, 在Remove Nth Node From End of List的Python3提交中击败了86.27% 的用户

猜你喜欢

转载自blog.csdn.net/weixin_42234472/article/details/84783580