还是一样,加一个虚拟头节点统一删除操作。还有就是找准删除结点的前面一个结点。
这个题简单,可以遍历知道个数,再操作。不过我推荐双指针做法,看起来高级。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyhead = new ListNode(0);
dummyhead ->next = head;
ListNode* fast = dummyhead;
ListNode* slow = dummyhead;
int count = 0;
while(fast!=nullptr){
fast = fast->next;
++count;
if(count > n+1){
slow = slow->next;
}
}
ListNode* temp = slow->next;
slow->next = slow->next->next;
delete temp;
return dummyhead->next;
}
};