Remove Nth Node From End of List
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.
从后往前数,删除第N个数
一开始想的比较简单,后来发现各种情况都有,比如,删除头,删除尾,删除中间,都是不一样的
提示出错之后修改了一下,通过
/**
* 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 (head->next == NULL)
return NULL;
else
{
int length = 0;
ListNode * len = head;
while (len)
{
length++;
len = len->next;
}
if (length == n)
{
head = head->next;
return head;
}
else
{
ListNode * p = head;
ListNode * p2 = head;
int position = length - n;
for (int i = 1; i < position; i++)
{
p = p->next;
p2 = p2->next;
}
p = p->next;
if (p->next==NULL)
{
p2->next = NULL;
return head;
}
else
{
p2->next = p->next;
delete p;
return head;
}
}
}
}
};