思路一:用map容器记录某一号节点是什么节点,然后修改即可。
class Solution {
public:
map<int, ListNode*>m;
ListNode *removeNthFromEnd(ListNode *head, int n) {
if(head == nullptr)
return nullptr;
ListNode * p = head;
int num = 0;
while(p){
m[num] = p;//记录num号节点
num++;
p =p->next;
}
if(n > num)
return head;
if(n == num)
return head->next;
//被删除的节点是m[num - n],修改其前面的节点和后面的节点即可
m[num - n - 1]->next = m[num - n + 1];//修改即可
delete m[num - n];
return head;
}
};
思路二:快指针。先让快指针走n-1步,然后快慢指针一起走,直到快指针走到末尾,此时的慢指针指向的节点就是要删除的节点。
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
if(head == nullptr || n <= 0)
return head;
ListNode * slow = head, *fast = head;
ListNode * pre = slow;//慢指针的前驱节点
for(int i = 0; i < n - 1; i++){//快指针先走n-1步数
if(fast == nullptr)
break;
fast = fast->next;
}
if(fast == nullptr )//n > 链表长度
return head;
while(fast->next){//快慢指针一起走
fast =fast ->next;
pre = slow;//记录慢指针前驱
slow = slow->next;
}
if(pre == slow ){//删除的节点是一个节点
return pre->next;//返回第二个节点即可
}
pre ->next = slow->next;//该指针域
delete slow;
return head;
}
};