在本教程中,我们将学习如何删除链表中的中间节点。
解决问题的方法很简单。我们将有两个指针,一个指针一次移动一个节点,另一个指针一次移动两个节点。到第二个指针到达最后一个节点时,第一个指针将位于链接列表的中间。
让我们看看解决问题的步骤。
为链接列表节点编写一个结构节点。
用伪数据初始化链表。
编写函数以删除链接列表。
用链接的列表头指针初始化两个指针(慢速和快速)。
遍历链接列表,直到快速指针到达末尾。
将慢速指针移动到下一个节点。
将快速指针移动到下一个节点的下一个节点。
返回头指针
打印链接列表。
让我们看一下代码。
#include <bits/stdc++.h> using namespace std; struct Node { int data; struct Node* next; }; struct Node* deleteMiddleNode(struct Node* head) { if (head == NULL) { return NULL; } if (head->next == NULL) { delete head; return NULL; } struct Node* slow_ptr = head; struct Node* fast_ptr = head; struct Node* prev; while (fast_ptr != NULL && fast_ptr->next != NULL) { fast_ptr = fast_ptr->next->next; prev = slow_ptr; slow_ptr = slow_ptr->next; } prev->next = slow_ptr->next; delete slow_ptr; return head; } void printLinkedList(struct Node* node) { while (node != NULL) { cout << node->data << " -> "; node = node->next; } cout << "Null" << endl; } Node* newNode(int data) { struct Node* temp = new Node; temp->data = data; temp->next = NULL; return temp; } int main() { struct Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); head->next->next->next->next->next = newNode(6); cout << "删除中间节点之前的链接列表: "; printLinkedList(head); head = deleteMiddleNode(head); cout << "删除中间节点后的链接列表: "; printLinkedList(head); return 0; }输出结果
如果执行上述程序,则将得到以下结果。
删除中间节点之前的链接列表: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> Null 删除中间节点后的链接列表: 1 -> 2 -> 3 -> 5 -> 6 -> Null