思路分析
常规解法:双指针与栈,两种解法
题解1
/**
* 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) {
stack<ListNode*> stk;
ListNode* new_head = new ListNode(0);
int i = 0;
while(head){
stk.push(head);
head = head->next;
}
while(!stk.empty()){
i += 1;
if(i == n){
stk.pop();
continue;
}
ListNode* temp = stk.top();
stk.pop();
ListNode* cur = new_head->next;
new_head->next = temp;
temp->next = cur;
}
return new_head->next;
}
};
题解2
/**
* 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 *new_head = head, *fast = head, *slow = head, *pre = NULL;
while(n--)
fast = fast->next;
if(fast == NULL)
return head->next;
while(fast){
fast = fast->next;
pre = slow;
slow = slow->next;
}
pre->next = slow->next;
return head;
}
};