File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
remove-nth-node-from-end-of-list Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ class ListNode {
2
+ val : number ;
3
+ next : ListNode | null ;
4
+ constructor ( val ?: number , next ?: ListNode | null ) {
5
+ this . val = val === undefined ? 0 : val ;
6
+ this . next = next === undefined ? null : next ;
7
+ }
8
+ }
9
+
10
+ /**
11
+ * https://leetcode.com/problems/remove-nth-node-from-end-of-list
12
+ * T.C. O(N)
13
+ * S.C. O(1)
14
+ */
15
+ function removeNthFromEnd ( head : ListNode | null , n : number ) : ListNode | null {
16
+ let first = head ;
17
+ let second = head ;
18
+
19
+ for ( let i = 0 ; i < n ; i ++ )
20
+ first = first ! . next ;
21
+
22
+ if ( ! first )
23
+ return head ! . next ;
24
+
25
+ while ( first . next ) {
26
+ first = first . next ;
27
+ second = second ! . next ;
28
+ }
29
+
30
+ second ! . next = second ! . next ! . next ;
31
+
32
+ return head ;
33
+ }
You can’t perform that action at this time.
0 commit comments