题目:
方法:采用双指针,定义一个dummy结点处理
注意点:pre指针需要指向需要删除元素的前一个元素,同时用完tmp指针需要及时让他指向空。
code:
/**
* 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(-1);
dummyhead->next=head;
ListNode* cur=dummyhead;
while(n--)
{
cur=cur->next;
}
ListNode* pre=dummyhead;
while(cur->next)
{
cur=cur->next;
pre=pre->next;
}
ListNode*tmp=pre->next;
pre->next=pre->next->next;
delete tmp;
tmp=nullptr;
head=dummyhead->next;
delete dummyhead;
return head;
}
};