File tree Expand file tree Collapse file tree 1 file changed +18
-23
lines changed Expand file tree Collapse file tree 1 file changed +18
-23
lines changed Original file line number Diff line number Diff line change 11
11
*/
12
12
13
13
function removeNthFromEnd ( head : ListNode | null , n : number ) : ListNode | null {
14
- let runner = head ;
15
- let c = 0 ;
16
-
17
- while ( c != n && runner != null ) {
18
- c ++ ;
19
- runner = runner . next ;
20
- }
21
-
22
- if ( runner == null ) {
23
- return head . next ;
24
- }
25
-
26
- let tail = head ;
27
-
28
- while ( runner . next != null ) {
29
- runner = runner . next ;
30
- tail = tail . next ;
31
- }
32
-
33
- tail . next = tail . next . next ;
34
-
35
- return head ;
36
- }
14
+ let dummy : ListNode = new ListNode ( 0 , head )
15
+ let left = dummy
16
+ let right = head
17
+
18
+ while ( n > 0 ) {
19
+ right = right . next
20
+ n -= 1
21
+ }
22
+
23
+ while ( right ) {
24
+ left = left . next
25
+ right = right . next
26
+ }
27
+
28
+ // delete
29
+ left . next = left . next . next
30
+ return dummy . next
31
+ } ;
You can’t perform that action at this time.
0 commit comments