在 C++ 程序中删除链表中间节点
在本教程中,我们将学习如何在链表中删除中间节点。
问题的解决方案很简单。我们将使用两个指针,一个每次移动一个节点,另一个每次移动两个节点。当第二个指针到达最后一个节点时,第一个指针将位于链表的中间。
让我们看看解决问题的步骤。
为链表节点编写一个结构体 Node。
使用虚拟数据初始化链表。
编写一个函数来删除链表。
用链表头指针初始化两个指针(slow 和 fast)。
遍历链表,直到 fast 指针到达末尾。
将 slow 指针移动到下一个节点。
将 fast 指针移动到下下一个节点。
返回头指针
打印链表。
示例
让我们看看代码。
#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 << "Linked list before deleting middle node: ";
printLinkedList(head);
head = deleteMiddleNode(head);
cout << "Linked List after deleting middle node: ";
printLinkedList(head);
return 0;
}输出
如果执行上述程序,您将获得以下结果。
Linked list before deleting middle node: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> Null Linked List after deleting middle node: 1 -> 2 -> 3 -> 5 -> 6 -> Null
结论
如果您在教程中有任何疑问,请在评论区提出。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP