用c++写双向循环链表
时间: 2024-04-30 16:18:39 浏览: 88
以下是用C++实现双向循环链表的代码:
```cpp
#include <iostream>
using namespace std;
// 双向循环链表节点结构体
struct Node {
int data;
Node *prev;
Node *next;
};
class DoubleLinkedList {
private:
Node *head; // 头节点
Node *tail; // 尾节点
int size; // 链表长度
public:
DoubleLinkedList() {
head = nullptr;
tail = nullptr;
size = 0;
}
// 在链表末尾添加节点
void addNode(int data) {
Node *newNode = new Node();
newNode->data = data;
newNode->prev = tail;
newNode->next = head;
if (size == 0) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
head->prev = newNode;
tail = newNode;
}
size++;
}
// 在指定位置插入节点
void insertNode(int index, int data) {
if (index < 0 || index > size) {
cout << "Invalid index" << endl;
return;
}
if (index == 0) {
addNode(data);
return;
}
if (index == size) {
Node *newNode = new Node();
newNode->data = data;
newNode->prev = tail;
newNode->next = head;
tail->next = newNode;
head->prev = newNode;
tail = newNode;
size++;
return;
}
Node *cur = head;
for (int i = 0; i < index; i++) {
cur = cur->next;
}
Node *newNode = new Node();
newNode->data = data;
newNode->prev = cur->prev;
newNode->next = cur;
cur->prev->next = newNode;
cur->prev = newNode;
size++;
}
// 删除指定位置的节点
void deleteNode(int index) {
if (index < 0 || index >= size) {
cout << "Invalid index" << endl;
return;
}
if (index == 0) {
head = head->next;
tail->next = head;
head->prev = tail;
size--;
return;
}
if (index == size - 1) {
tail = tail->prev;
tail->next = head;
head->prev = tail;
size--;
return;
}
Node *cur = head;
for (int i = 0; i < index; i++) {
cur = cur->next;
}
cur->prev->next = cur->next;
cur->next->prev = cur->prev;
size--;
}
// 获取指定位置的节点值
int get(int index) {
if (index < 0 || index >= size) {
cout << "Invalid index" << endl;
return -1;
}
Node *cur = head;
for (int i = 0; i < index; i++) {
cur = cur->next;
}
return cur->data;
}
// 获取链表长度
int getSize() {
return size;
}
// 打印链表
void printList() {
if (size == 0) {
cout << "Empty list" << endl;
return;
}
Node *cur = head;
for (int i = 0; i < size; i++) {
cout << cur->data << " ";
cur = cur->next;
}
cout << endl;
}
};
int main() {
DoubleLinkedList list;
list.addNode(1);
list.addNode(2);
list.addNode(3);
list.addNode(4);
list.printList(); // Output: 1 2 3 4
list.insertNode(2, 5);
list.printList(); // Output: 1 2 5 3 4
list.deleteNode(3);
list.printList(); // Output: 1 2 5 4
cout << "Size: " << list.getSize() << endl; // Output: Size: 4
cout << "Value at index 2: " << list.get(2) << endl; // Output: Value at index 2: 5
return 0;
}
```
阅读全文