📅  最后修改于: 2023-12-03 14:39:54.909000             🧑  作者: Mango
本文介绍如何使用C++编写一个删除链表中间节点的程序。
以下代码演示了如何删除链表中间节点。假设我们的链表中有$n$个元素,我们希望删除第$\lfloor n/2 \rfloor$个元素。具体实现如下:
ListNode* deleteMiddleNode(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return nullptr;
}
ListNode* slow = head;
ListNode* fast = head;
ListNode* prev = nullptr;
while (fast != nullptr && fast->next != nullptr) {
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
prev->next = slow->next;
return head;
}
在这个程序中,我们使用了快慢指针的技巧来找到中间元素。同时,我们还需要维护一个指针prev,用于删除中间节点。
为了验证我们的程序,以下是一个简单的测试用例:
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x): val(x), next(nullptr) {}
};
void printList(ListNode* head) {
if (head == nullptr) {
cout << "null" << endl;
} else {
cout << head->val;
ListNode* node = head->next;
while (node != nullptr) {
cout << " -> " << node->val;
node = node->next;
}
cout << endl;
}
}
ListNode* deleteMiddleNode(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return nullptr;
}
ListNode* slow = head;
ListNode* fast = head;
ListNode* prev = nullptr;
while (fast != nullptr && fast->next != nullptr) {
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
prev->next = slow->next;
return head;
}
int main() {
// create a linked list
ListNode* node1 = new ListNode(1);
ListNode* node2 = new ListNode(2);
ListNode* node3 = new ListNode(3);
ListNode* node4 = new ListNode(4);
ListNode* node5 = new ListNode(5);
node1->next = node2;
node2->next = node3;
node3->next = node4;
node4->next = node5;
// print the original linked list
cout << "Original linked list: ";
printList(node1);
// delete middle node
ListNode* newHead = deleteMiddleNode(node1);
// print the updated linked list
cout << "Updated linked list: ";
printList(newHead);
return 0;
}
输出结果如下:
Original linked list: 1 -> 2 -> 3 -> 4 -> 5
Updated linked list: 1 -> 2 -> 4 -> 5
可以看到,中间的节点3已经被成功删除了。