0%

Leetcode 19 删除链表的倒数第 N 个结点

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

找到链表的倒数第 n 个节点,然后删除该节点即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
count = 0
current = head
while current:
count += 1
current = current.next
pos = count - n
index = 0
current = head

if pos == 0:
return head.next

while current:
index += 1
if index == pos and current.next is not None:
current.next = current.next.next
break
else:
current = current.next
return head