给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
示例 1:
输入:head = [1,2,3,4,5], n = 2 输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1 输出:[]
示例 3:
输入:head = [1,2], n = 1 输出:[1]
思路
双指针,快指针判断范围,慢指针定位;哈希;递归。
代码
递归
class Solution {
public:
int step = 0;
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(head)
head->next = removeNthFromEnd(head->next, n);
else
return nullptr;
++step;
if(step == n)
return head->next;
else
return head;
}
};
双指针
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
unordered_map<int, ListNode*> hashmap;
int step = 0;
ListNode* fast = head;
ListNode* slow = head;
while(fast!=nullptr)
{
fast = fast->next;
++step;
}
fast = head;
if((step-=n))
{
for(int i=0; i<step; ++i)
{
if(i == step-1)
slow = fast;
fast = fast->next;
}
slow->next = fast->next;
}
else
head = head->next;
return head;
}
};
哈希
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
unordered_map<int, ListNode*> hashmap;
int cnt = 0;
ListNode* node = head;
while(node != nullptr)
{
++cnt;
hashmap[cnt] = node;
node = node->next;
}
if(n!=cnt)
hashmap[cnt-n]->next =hashmap[cnt-n+1]->next;
else
head = head->next;
return head;
}
};