-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRemove Nth Node From End of List
60 lines (48 loc) · 1.22 KB
/
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
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n)
{
//if Single element list, thus returning empty list
if(head.next == null)
return null;
ListNode ptr = head;
ListNode ptr2 = head;
int len = 0;
//finding the lenght of the list
while(ptr != null)
{
len++;
ptr = ptr.next;
}
//required index
int index = len - n;
ptr = head;
boolean start = false;
while(true)
{
if(index == 0)
{
// if head element
if(ptr == head)
{
ptr2 = ptr2.next;
ptr.next = null;
head = ptr2;
break;
}
else
{
ptr2.next = ptr.next;
ptr.next = null;
break;
}
}
index--;
//for letting the second pointer start late
if(start)
ptr2 = ptr2.next;
start = true;
ptr = ptr.next;
}
return head;
}
}