Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes
Created June 7, 2017 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InterviewBytes/e539bb71be151b77261382c342de7367 to your computer and use it in GitHub Desktop.
Save InterviewBytes/e539bb71be151b77261382c342de7367 to your computer and use it in GitHub Desktop.
Remove Nth node from the end
package com.interviewbytes.linkedlists;
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
package com.interviewbytes.linkedlists;
public class RemoveNthNode {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode sentinel = new ListNode(0);
sentinel.next = head;
ListNode slow = sentinel;
ListNode fast = sentinel;
int i = 0;
while (i <= n) {
fast = fast.next;
i++;
}
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return sentinel.next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment