Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

19. Remove Nth Node From End of List

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Follow up: Could you do this in one pass?

Example 1:

1
2
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

Example 2:

1
2
Input: head = [1], n = 1
Output: []

Example 3:

1
2
Input: head = [1,2], n = 1
Output: [1]

移除串列倒數第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
Time: O(n), Space: O(1)

# 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: ListNode, n: int) -> ListNode:
dummy=ListNode(0)
dummy.next=head
pos_0=pos_n=dummy # ListNode->head 0

for i in range(n): # 0, 1, 2
pos_n=pos_n.next # n=1 n=2

while pos_n.next:
pos_0=pos_0.next # n= 0
pos_n=pos_n.next # n= 2
print(pos_0.val) # n=3
print(pos_n.val) # n=5
pos_0.next=pos_0.next.next

return dummy.next

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels