19.删除链表的倒数第N个节点

19.删除链表倒数第N个节点
整理一下这题的思路,题目很清晰,给你一个链表,删除链表的倒数第 n个结点,并且返回链表的头结点。

第一反应暴力算出一共几个节点length,然后再从头到length - n遍历一次。

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        length = 0
        pre = __head = ListNode(next=head)
        cur = head
        while cur != None:
            length += 1
            cur = cur.next
        cur = __head.next
        for _ in range(length - n):
            cur = cur.next
            pre = pre.next
        pre.next = cur.next
        return __head.next

后面观察发现,如果先让curn步,然后让precur同时走,那么但cur走到None的时候,刚好pre是在需要删除的元素的前一个位置。
注意:pre的初始是指向头结点的,所以curpre其实相差了n + 1

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        pre = __head = ListNode(next=head)
        cur = head
        for _ in range(n):
            cur = cur.next
        while cur != None:
            cur = cur.next
            pre = pre.next
        pre.next = pre.next.next
        return __head.next

你可能感兴趣的:(刷题,链表,数据结构,leetcode,python,算法)