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.
方法一:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
if (n==0 || !head) return head;
ListNode *pre = NULL;
ListNode *first=head;
ListNode *last =head;
int index = 1;
while (last->next && index <n){
last = last->next;
index++;
}
if (index < n) return head;
while (last->next){
pre = first;
first = first->next;
last = last->next;
}
if (pre) {
pre->next = first->next;
delete first;
return head;
}
pre = first->next;
delete head;
return pre;
}
};
方法二:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
if (n==0 || !head) return head;
int index = 0;
ListNode *p = head;
ListNode *first,*last;
last = head;
while (last && index<=n ){
index ++;
last = last->next;
}
if (index ==n+1) {
first = head;
while (last){
last = last->next;
first = first->next;
}
p = first->next;
first->next = p->next;
delete p;
return head;
} else if (index ==n){
p = head;
head = head->next;
delete p;
return head;
} else {
return head;
}
}
};