-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprblm19.java
More file actions
61 lines (57 loc) · 1.63 KB
/
prblm19.java
File metadata and controls
61 lines (57 loc) · 1.63 KB
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
public class prblm19 {
public static void main(String[] args) {
ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(2);
l1.next = l2;
ListNode head = l1;
ListNode afterremoval = removeNthFromEnd(head, 2);
printList(afterremoval);
// ListNode l1 = new ListNode(1);
// ListNode l2 = new ListNode(2);
// ListNode l3 = new ListNode(3);
// ListNode l4 = new ListNode(4);
// ListNode l5 = new ListNode(5);
// l1.next = l2;
// l2.next = l3;
// l3.next = l4;
// l4.next = l5;
// ListNode head = l1;
// printList(head);
// ListNode afterremoval = removeNthFromEnd(head, 2);
// printList(afterremoval);
}
public static ListNode removeNthFromEnd(ListNode head, int n) {
ListNode curr = head;
int length = findLength(curr);
if(length == 1){
return null;
}
if(length == n){
return head.next;
}
int count = 0;
while(count < (length - n - 1)){
curr = curr.next;
count++;
}
curr.next = curr.next.next;
return head;
}
public static int findLength(ListNode head){
ListNode curr = head;
int length = 0;
while(curr != null){
length++;
curr = curr.next;
}
return length;
}
public static void printList(ListNode head){
ListNode curr = head;
while(curr != null){
System.out.print(curr.val + " ");
curr = curr.next;
}
System.out.println();
}
}