19. Remove Nth Node From End of List
题目描述
题目解读
- 一开始做的时候以为一直是倒数第二个,我想这不是很容易,结果没看清题目,那个bug改的痛啊,以及要纪念一下第一次不看讨论区独立完成的代码。
代码
/**
* 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* cur = head->next;
ListNode* pre = head;
int num = 0;
while(pre!=nullptr)
{
num++;
pre = pre->next;
}
cout<<num<<endl;
pre = head;
int i = 0;
if(num == 1 && n == 1) return nullptr; // 当n=num=1,就是空的了
else if(num < n) return nullptr;
else if(num == n)
{
// cout<<"**"<<endl;
head = pre->next;
return head;
}
while(i < num-n-1 )
{
pre = cur;
cur = cur->next;
i++;
// cout<<pre->val<<":"<<cur->val<<endl;
}
pre->next = cur->next;
return head;
}
};