Skip to content

Instantly share code, notes, and snippets.

@cxtadment
Last active September 1, 2015 16:25
Show Gist options
  • Save cxtadment/1ac883f4cbe12c5b945a to your computer and use it in GitHub Desktop.
Save cxtadment/1ac883f4cbe12c5b945a to your computer and use it in GitHub Desktop.
/**
* 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