File tree Expand file tree Collapse file tree 1 file changed +11
-11
lines changed
0019-remove-nth-node-from-end-of-list Expand file tree Collapse file tree 1 file changed +11
-11
lines changed Original file line number Diff line number Diff line change 1- # Approach 2 - One Pass Algorithm
1+ # Approach 2: One Pass algorithm
22
3- # Time: O(L), L = no. of nodes
3+ # L = length of linked list
4+ # Time: O(L)
45# Space: O(1)
56
67# Definition for singly-linked list.
78# class ListNode:
89# def __init__(self, val=0, next=None):
910# self.val = val
1011# self.next = next
12+
1113class Solution :
1214 def removeNthFromEnd (self , head : Optional [ListNode ], n : int ) -> Optional [ListNode ]:
13- dummy = ListNode (val = 0 , next = head )
14-
15+ dummy = ListNode (0 )
16+ dummy .next = head
17+
1518 first = dummy
1619 second = dummy
17-
18- # Advances first pointer so that the gap between first and second is n nodes apart
19- for i in range (n + 1 ):
20+
21+ for i in range (n + 1 ):
2022 first = first .next
21-
22- # Move first to the end, maintaining the gap
23+
2324 while first is not None :
2425 first = first .next
2526 second = second .next
26-
27+
2728 second .next = second .next .next
2829 return dummy .next
29-
You can’t perform that action at this time.
0 commit comments