Problem
leetcode链接problem
Code
本来想法就是第一遍遍历来看看长度是多少,然后第二遍直接把改删的指针变过去,然后题中又出现了一些奇奇怪怪的问题,一些特殊项,就拿出来单独处理掉了。
/**
* 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) {
ListNode* constHead = head;
ListNode* change = constHead;
int len = 0;
//int label = 0;
while (change != nullptr)
{
len++;
change = change->next;
}//记录len的长度,然后删除节点就只要删长度减n处不就可以了?
if(len == 1 && n == 1)
{
return nullptr;
}
if(len == 2)
{
if(n == 1)
{
constHead->next = nullptr;
return constHead;
}
else
{
return constHead->next;
}
}
if(len == n)
{
return constHead->next;
}
change = constHead;
for (int i = 0; i < len - n - 1; ++i) {
change = change->next;
}
change->next = change->next->next;
return constHead;
}
};