-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path19. Remove Nth Node From End of List
68 lines (60 loc) · 1.54 KB
/
19. Remove Nth Node From End of List
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode curr = head;
ListNode prev = null;
ListNode next = curr.next;
while(curr != null){
curr.next = prev;
prev = curr;
curr = next;
if(next != null){
next = next.next;
}
}
head = prev;
ListNode temp = head;
// while(temp != null){
// System.out.println(temp.val);
// temp = temp.next;
// }
// return head;
if(head.next == null && n==1){
head = null;
return head;
}
if( n == 1){
head = head.next;
curr = head;
prev = null;
next = curr.next;
while(curr != null){
curr.next = prev;
prev = curr;
curr = next;
if(next != null){
next = next.next;
}
}
head = prev;
return head;
}
for(int i=0;i<n-2;i++){
temp = temp.next;
}
ListNode temp1 = temp.next.next;
temp.next = temp1;
curr = head;
prev = null;
next = curr.next;
while(curr != null){
curr.next = prev;
prev = curr;
curr = next;
if(next != null){
next = next.next;
}
}
head = prev;
return head;
}
}