C++ 环形双向链表删除操作:高效实现与优化
#include <iostream>
using namespace std;
struct Node {
int data;
Node *prev, *next;
};
// 创建一个新的节点
Node* newNode(int data) {
Node* node = new Node;
node->data = data;
node->prev = node->next = node;
return node;
}
// 在链表中插入一个节点
void insert(Node** head, int data) {
if (*head == NULL) {
*head = newNode(data);
return;
}
Node* new_node = newNode(data);
new_node->next = *head;
new_node->prev = (*head)->prev;
(*head)->prev->next = new_node;
(*head)->prev = new_node;
}
// 删除链表中的节点
void deleteNode(Node** head, int data) {
if (*head == NULL) {
return;
}
Node* current = *head;
bool found = false;
do {
if (current->data == data) {
found = true;
// 如果是最后一个节点
if (current->next == current) {
*head = NULL;
} else {
current->prev->next = current->next;
current->next->prev = current->prev;
if (*head == current) {
*head = current->next;
}
}
delete current;
current = *head; // 重置 current 为头节点,继续遍历
} else {
current = current->next;
}
} while (current != *head);
if (!found) {
cout << -1 << endl;
}
}
// 打印链表
void printList(Node* head) {
if (head == NULL) {
return;
}
Node* current = head;
do {
cout << current->data << ' ';
current = current->next;
} while (current != head);
cout << endl;
}
int main() {
Node* head = NULL;
int data;
cin >> data;
while (data != -1) {
insert(&head, data);
cin >> data;
}
cin >> data;
while (data != -1) {
deleteNode(&head, data);
printList(head);
cin >> data;
}
printList(head);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/lHEL 著作权归作者所有。请勿转载和采集!