力扣https://leetcode.cn/problems/remove-nth-node-from-end-of-list/ 本题使用虚拟头结点,定义两个指针fast和slow,初始两个指针都指向虚拟头结点,首先fast指针先走n+1步,然后fast和slow同时移动,直到fast指针指向链表末尾也即是NULL,这时slow指针正好指向待删除节点的上一个节点。此时进行删除结点操作即可。
//
// Created by lwj on 2023-03-29.
//
#include <iostream>
using namespace std;
// 定义链表节点
struct ListNode {
int val;
ListNode *next;
ListNode(int val) : val(val), next(NULL) {}
};
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head,int n) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* slow = dummyHead;
ListNode* fast = dummyHead;
// 让fast先走n步
while (n-- && fast != NULL) {
fast = fast->next;
}
// 让fast在往前走一步,使得下面fast和slow同时走的时候,slow停在要删除节点的前一个节点
fast = fast->next;
while (fast != NULL) {
fast = fast->next;
slow = slow->next;
}
// 在删除这个节点的时候 先用temp将这个节点存下来 便于释放内存
ListNode* temp = slow->next;
slow->next = temp->next;
delete temp;
return dummyHead->next;
}
};
// 打印链表
void printList(ListNode* head) {
ListNode* cur = head;
while (cur != NULL) {
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
int main() {
// 创建链表
ListNode* head = new ListNode(1);
ListNode* node2 = new ListNode(2);
ListNode* node3 = new ListNode(3);
ListNode* node4 = new ListNode(4);
ListNode* node5 = new ListNode(5);
head->next = node2;
node2->next = node3;
node3->next = node4;
node4->next = node5;
// 打印原链表
cout << "Original list: " << endl;
printList(head);
// 移除倒数第二个结点
int n = 2;
Solution solution;
ListNode* newHead = solution.removeNthFromEnd(head, n);
// 打印移除后的链表
cout << "After removing the " << n << "th node from end: " << endl;
printList(newHead);
return 0;
}