Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions Java/Random_programs/LinkedList.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,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);
}
}
30 changes: 30 additions & 0 deletions Java/Random_programs/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@

class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}

public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode first = dummy;
ListNode second = dummy;

// Advance first pointer so that the gap between first and second is n nodes apart
for (int i = 0; i <= n; i++) {
first = first.next;
}

// Move first to the end, maintaining the gap
while (first != null) {
first = first.next;
second = second.next;
}

// Remove the nth node from the end
second.next = second.next.next;
return dummy.next;
}
}