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.
Use two pointers, when the first pointer reach the end, the second pointer place is the node to be removed.
The thing should be noticed is the head pointer.
java
public ListNode removeNthFromEnd(ListNode head, int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(n<=0) return head;
ListNode prve = new ListNode(0);
prve.next = head;
head = prve;
ListNode n1 = head.next, n2=head.next;
int k=n;
while(n2!=null && k>0){
n2 = n2.next;
k--;
}
if(k>0) return n1;
while(n2!=null){
n2 = n2.next;
n1 = n1.next;
prve = prve.next;
}
prve.next = n1.next;
return head.next;
}
Refactor: Sep/17/2014
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode newHead = new ListNode(-1);
newHead.next = head;
ListNode p1 = head;
while(n>1){
p1 = p1.next;
n--;
}
ListNode p3 = newHead;
while(p1.next!=null){
p1 = p1.next;
p3 = p3.next;
}
p3.next = p3.next.next;
return newHead.next;
}
c++
ListNode *removeNthFromEnd(ListNode *head, int n) {
ListNode *newHead = new ListNode(0);
newHead->next = head;
ListNode *p = newHead;
ListNode *d = newHead;
while(n>0){
d = d->next;
n--;
}
while(d->next!=NULL){
p = p->next;
d = d->next;
}
p->next = p->next->next;
return newHead->next;
}