Last active
September 1, 2015 16:25
-
-
Save cxtadment/1ac883f4cbe12c5b945a 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 postMark = head; | |
ListNode preMark = head; | |
for (int i = 0; i < n; i++) { | |
if (postMark == null) { | |
return null; | |
} | |
postMark = postMark.next; | |
} | |
if (postMark == null) { | |
return head.next; | |
} | |
while (postMark.next != null) { | |
postMark = postMark.next; | |
preMark = preMark.next; | |
} | |
preMark.next = preMark.next.next; | |
return head; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment