-
Notifications
You must be signed in to change notification settings - Fork 207
Expand file tree
/
Copy pathLinkedList.java
More file actions
68 lines (55 loc) · 1.73 KB
/
LinkedList.java
File metadata and controls
68 lines (55 loc) · 1.73 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
62
63
64
65
66
67
68
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class LinkedList {
public static ListNode removeNthFromEnd(ListNode head, int n) {
// Create a dummy node
ListNode dummy = new ListNode(0);
dummy.next = head;
// Initialize two pointers
ListNode first = dummy;
ListNode second = dummy;
// Move first pointer n+1 steps ahead
for (int i = 0; i <= n; i++) {
first = first.next;
}
// Move both pointers until first reaches the end
while (first != null) {
first = first.next;
second = second.next;
}
// Remove the nth node from the end
second.next = second.next.next;
// Return the modified list
return dummy.next;
}
// Helper function to print the linked list
public static void printList(ListNode head) {
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
System.out.println();
}
public static void main(String[] args) {
// Create a linked list: 1 -> 2 -> 3 -> 4 -> 5
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
// Print the original list
System.out.print("Original List: ");
printList(head);
// Remove the 2nd node from the end (4 in this case)
head = removeNthFromEnd(head, 2);
// Print the modified list
System.out.print("Modified List: ");
printList(head);
}
}