Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cxtadment/de17d70ea6cefdb796b1 to your computer and use it in GitHub Desktop.
Save cxtadment/de17d70ea6cefdb796b1 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 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