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