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.
死办法。。 有一点要注意, 见下面注释
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int cnt = 0;
int flag = 0;
ListNode* p = head;
if(!head)
return NULL;
if(head->next == NULL && n == 1)
return NULL;
while(head)
{
cnt++;
head = head->next;
}
ListNode* q = p;
while(q)
{
flag++;
if(n == 1) //这里是判断,如果删除的是尾结点,操作会不一样,而且也没有NEXT,直接写next就错了
{
if(flag ==(cnt - n))
q->next = NULL;
}
else
if(flag == (cnt - n + 1))
{
q->val = q->next->val;
q->next = q->next->next;
break;
}
q = q->next;
}
return p;
}
};
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode dum(0), *slow=&dum, *fast=head;
dum.next=head; //get the dum connected
// move the fast pointer according to the offset
for(int i=0; i<n; ++i) fast=fast->next;
while(fast) {
fast=fast->next;
slow=slow->next;
}
//now the slow pointer will be the n+1 th node from the end (may be the dum head)
fast=slow->next;
slow->next=fast->next;
delete fast; //remove the specified node
return dum.next;
}
};