#include <iostream>
struct Node {
int data;
Node* prev;
Node* next;
Node(int value) : data(value), prev(nullptr), next(nullptr) {}
};
class DoublyLinkedList {
private:
Node* head;
Node* tail;
public:
DoublyLinkedList() : head(nullptr), tail(nullptr) {}
void append(int value) {
Node* newNode = new Node(value);
if (head == nullptr) {
head = tail = newNode;
} else {
tail->next = newNode;
newNode->prev = tail;
tail = newNode;
}
}
void remove(int value) {
Node* current = head;
while (current != nullptr) {
if (current->data == value) {
if (current == head) {
head = current->next;
if (head != nullptr) {
head->prev = nullptr;
}
} else if (current == tail) {
tail = current->prev;
tail->next = nullptr;
} else {
current->prev->next = current->next;
current->next->prev = current->prev;
}
Node* temp = current;
current = current->next;
delete temp;
} else {
current = current->next;
}
}
}
void display() {
Node* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
};
int main() {
DoublyLinkedList myList;
myList.append(1);
myList.append(2);
myList.append(3);
myList.append(4);
myList.append(2);
myList.append(5);
myList.append(2);
std::cout << "Original list: ";
myList.display();
myList.remove(2);
std::cout << "List after remove: ";
myList.display();
return 0;
}
C++ 双向链表中删除与指定值相同的元素
最新推荐文章于 2024-04-18 09:57:52 发布