用c++编写一个有增加删除查找改写的双向循环链表
时间: 2024-02-29 11:51:21 浏览: 28
好的,下面是用C++编写的有增加、删除、查找和改写操作的双向循环链表。
```cpp
#include <iostream>
using namespace std;
struct Node {
int data;
Node* prev;
Node* next;
};
class DoublyLinkedList {
private:
Node* head;
Node* tail;
int size;
public:
DoublyLinkedList() {
head = nullptr;
tail = nullptr;
size = 0;
}
bool isEmpty() {
return size == 0;
}
int getSize() {
return size;
}
void add(int value) {
Node* newNode = new Node;
newNode->data = value;
newNode->prev = tail;
newNode->next = head;
if (isEmpty()) {
head = newNode;
tail = newNode;
head->prev = tail;
tail->next = head;
}
else {
tail->next = newNode;
head->prev = newNode;
tail = newNode;
}
size++;
}
void remove(int value) {
if (isEmpty()) {
cout << "The list is empty." << endl;
return;
}
Node* current = head;
while (current->data != value) {
current = current->next;
if (current == head) {
cout << "The value is not in the list." << endl;
return;
}
}
if (size == 1) {
head = nullptr;
tail = nullptr;
}
else if (current == head) {
head = head->next;
head->prev = tail;
tail->next = head;
}
else if (current == tail) {
tail = tail->prev;
tail->next = head;
head->prev = tail;
}
else {
current->prev->next = current->next;
current->next->prev = current->prev;
}
delete current;
size--;
}
Node* find(int value) {
if (isEmpty()) {
cout << "The list is empty." << endl;
return nullptr;
}
Node* current = head;
while (current->data != value) {
current = current->next;
if (current == head) {
cout << "The value is not in the list." << endl;
return nullptr;
}
}
return current;
}
void modify(int oldValue, int newValue) {
Node* node = find(oldValue);
if (node != nullptr) {
node->data = newValue;
}
}
void printList() {
if (isEmpty()) {
cout << "The list is empty." << endl;
return;
}
Node* current = head;
cout << "[ ";
do {
cout << current->data << " ";
current = current->next;
} while (current != head);
cout << "]" << endl;
}
~DoublyLinkedList() {
while (!isEmpty()) {
remove(head->data);
}
}
};
int main() {
DoublyLinkedList list;
list.add(1);
list.add(2);
list.add(3);
list.printList();
list.remove(2);
list.printList();
list.modify(3, 4);
list.printList();
return 0;
}
```
这个双向循环链表具有以下特点:
1. 支持增加、删除、查找和改写操作
2. 支持空链表的情况
3. 支持删除头节点、尾节点和中间节点
4. 支持查找不存在的值的情况
5. 支持在修改元素时,元素不存在的情况
6. 在析构函数中,链表会被完全销毁,所有节点的内存会被释放。