-
-
Save InterviewBytes/e539bb71be151b77261382c342de7367 to your computer and use it in GitHub Desktop.
Remove Nth node from the end
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.interviewbytes.linkedlists; | |
public class ListNode { | |
int val; | |
ListNode next; | |
ListNode(int x) { | |
val = x; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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