forked from sherigar/HacktoberFest-2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Remove Nth Node from end of list problem..java
79 lines (63 loc) · 1.95 KB
/
Remove Nth Node from end of list problem..java
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
69
70
71
72
73
74
75
76
77
78
79
import java.util.*;
public class LinkedList {
public static class ListNode {
int data;
ListNode next;
public ListNode(int data) {
this.data = data;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ListNode head = null;
ListNode tail = null;
System.out.println("Enter integers to create a linked list. Enter -1 to stop.");
int userInput;
while (true) {
System.out.print("Enter an integer: ");
userInput = scanner.nextInt();
if (userInput == -1) {
break;
}
ListNode newNode = new ListNode(userInput);
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
}
System.out.println("Enter the value of n");
int n=scanner.nextInt();
ListNode head1=removeNthFromEnd(head,n);
printLinkedList(head1);
scanner.close();
}
public static void printLinkedList(ListNode head) {
ListNode current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
public static ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode fast = dummy;
ListNode slow = dummy;
// Move the fast pointer n nodes ahead.
for (int i = 0; i <= n; i++) {
fast = fast.next;
}
// Move both pointers until the fast pointer reaches the end.
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
// Remove the nth node from the end by adjusting the pointers.
slow.next = slow.next.next;
return dummy.next;
}
}