Created
September 1, 2015 16:30
-
-
Save cxtadment/de17d70ea6cefdb796b1 to your computer and use it in GitHub Desktop.
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
/** | |
* Definition for ListNode. | |
* public class ListNode { | |
* int val; | |
* ListNode next; | |
* ListNode(int val) { | |
* this.val = val; | |
* this.next = null; | |
* } | |
* } | |
*/ | |
public class Solution { | |
/** | |
* @param head: The first node of linked list. | |
* @param n: An integer. | |
* @return: The head of linked list. | |
*/ | |
ListNode removeNthFromEnd(ListNode head, int n) { | |
// write your code here | |
if (head == null || n < 0) { | |
return null; | |
} | |
ListNode dummyHead = new ListNode(0); | |
dummyHead.next = head; | |
ListNode preHead = dummyHead; | |
for (int i = 0; i < n; i++) { | |
if (head == null) { | |
return null; | |
} | |
head = head.next; | |
} | |
while (head != null) { | |
head = head.next; | |
preHead = preHead.next; | |
} | |
preHead.next = preHead.next.next; | |
return dummyHead.next; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment