Created
May 17, 2013 16:07
-
-
Save daifu/5600122 to your computer and use it in GitHub Desktop.
Remove Nth Node From End of List
This file contains hidden or 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
/* | |
Given a linked list, remove the nth node from the end of list and return its head. | |
For example, | |
Given linked list: 1->2->3->4->5, and n = 2. | |
After removing the second node from the end, the linked list becomes 1->2->3->5. | |
Note: | |
Given n will always be valid. | |
Try to do this in one pass. | |
Algorithm: | |
1. 3 pointers, last, mid and ahead, the distance between mid and ahead is n and last is just behind the mid | |
2. It needs dummy node to handle corner case. | |
*/ | |
/** | |
* Definition for singly-linked list. | |
* public class ListNode { | |
* int val; | |
* ListNode next; | |
* ListNode(int x) { | |
* val = x; | |
* next = null; | |
* } | |
* } | |
*/ | |
public class Solution { | |
public ListNode removeNthFromEnd(ListNode head, int n) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
if(head == null) return null; | |
ListNode ahead = head; | |
ListNode mid = head; | |
ListNode dummy = new ListNode(0); | |
dummy.next = head; | |
ListNode last = dummy; | |
while(n > 0 && ahead != null) { | |
ahead = ahead.next; | |
n--; | |
} | |
while(ahead != null) { | |
ahead = ahead.next; | |
last = mid; | |
mid = mid.next; | |
} | |
// delete mid | |
last.next = mid.next; | |
return dummy.next; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment