File tree Expand file tree Collapse file tree 1 file changed +22
-31
lines changed Expand file tree Collapse file tree 1 file changed +22
-31
lines changed Original file line number Diff line number Diff line change 10
10
*/
11
11
class Solution {
12
12
public ListNode removeNthFromEnd (ListNode head , int n ) {
13
- ListNode dummy = new ListNode ( 0 );
14
- dummy . next = head ;
15
- ListNode first = dummy ;
16
- ListNode second = dummy ;
13
+ if ( n == 0 || head == null )
14
+ return head ;
15
+ if ( n == 1 && head . next == null )
16
+ return null ;
17
17
18
- for (int i = 0 ; i < n ; i ++) {
19
-
20
- // If count of nodes in the given
21
- // linked list is <= N
22
- if (second .next == null ) {
23
-
24
- // If count = N i.e. delete the head node
25
- if (i == n - 1 )
26
- first = first .next ;
27
-
28
- }
29
- second = second .next ;
30
- }
31
-
32
- // Increment both the pointers by one until
33
- // second pointer reaches the end
34
- while (second .next != null ) {
35
- first = first .next ;
36
- second = second .next ;
37
- }
38
-
39
- // First must be pointing to the
40
- // Nth node from the end by now
41
- // So, delete the node first is pointing to
42
- first .next = first .next .next ;
43
- return dummy .next ;
18
+ ListNode fast =head ;
19
+ ListNode slow =head ;
20
+ while (n -->0 )
21
+ fast =fast .next ;
22
+ if (fast ==null )
23
+ return slow .next ;
24
+ while (fast .next !=null )
25
+ {
26
+ fast =fast .next ;
27
+ slow =slow .next ;
28
+ }
29
+
30
+ ListNode fwd =slow .next ;
31
+ slow .next =fwd .next ;
32
+ fwd .next =null ;
33
+
34
+ return head ;
44
35
}
45
36
46
- }
37
+ }
You can’t perform that action at this time.
0 commit comments