File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ from typing import Optional
2+
3+ # Definition for singly-linked list.
4+ # class ListNode:
5+ # def __init__(self, val=0, next=None):
6+ # self.val = val
7+ # self.next = next
8+
9+
10+ class Solution :
11+ def removeNthFromEnd (self , head : Optional [ListNode ], n : int ) -> Optional [ListNode ]:
12+ """
13+ LeetCode 19. Remove Nth Node From End of List
14+
15+ Approach:
16+ 1. Reverse the linked list.
17+ 2. The nth node from the end becomes the nth node from the beginning.
18+ 3. Remove the nth node.
19+ 4. Reverse the list again to restore the original order.
20+
21+ Example:
22+ Original:
23+ 1 -> 2 -> 3 -> 4 -> 5
24+
25+ Reverse:
26+ 5 -> 4 -> 3 -> 2 -> 1
27+
28+ Remove 2nd node:
29+ 5 -> 3 -> 2 -> 1
30+
31+ Reverse again:
32+ 1 -> 2 -> 3 -> 5
33+
34+ Time Complexity:
35+ O(n)
36+ - First reverse: O(n)
37+ - Remove node: O(n)
38+ - Second reverse: O(n)
39+
40+ Overall: O(n)
41+
42+ Space Complexity:
43+ O(1)
44+ """
45+
46+ # -------------------------------
47+ # Step 1: Reverse the linked list
48+ # -------------------------------
49+ prev = None
50+ curr = head
51+
52+ while curr :
53+ nxt = curr .next
54+ curr .next = prev
55+ prev = curr
56+ curr = nxt
57+
58+ # 'prev' is the new head of the reversed list
59+ head = prev
60+
61+ # -----------------------------------------
62+ # Step 2: Remove the nth node from the front
63+ # -----------------------------------------
64+ prev_node = None
65+ curr = head
66+ index = 1
67+
68+ while index < n and curr :
69+ prev_node = curr
70+ curr = curr .next
71+ index += 1
72+
73+ # If removing the first node of the reversed list
74+ if prev_node is None :
75+ head = head .next
76+ else :
77+ prev_node .next = curr .next
78+
79+ # -------------------------------
80+ # Step 3: Reverse the list again
81+ # -------------------------------
82+ prev = None
83+ curr = head
84+
85+ while curr :
86+ nxt = curr .next
87+ curr .next = prev
88+ prev = curr
89+ curr = nxt
90+
91+ # Return the restored list
92+ return prev
You can’t perform that action at this time.
0 commit comments