数据结构课程设计c++双向链表
时间: 2024-04-09 17:24:56 浏览: 13
数据结构课程设计中,C++双向链表是一个常见的数据结构之一。它是一种线性数据结构,由多个节点组成,每个节点包含两个指针,一个指向前一个节点,一个指向后一个节点。双向链表相比于单向链表,可以实现双向遍历。
在C++中,可以通过定义一个双向链表类来实现双向链表的功能。以下是一个简单的C++双向链表的实现示例:
```cpp
#include <iostream>
// 双向链表节点定义
class Node {
public:
int data;
Node* prev;
Node* next;
};
// 双向链表类定义
class DoublyLinkedList {
private:
Node* head; // 头节点指针
public:
DoublyLinkedList() {
head = nullptr;
}
// 在链表头部插入节点
void insertAtHead(int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->prev = nullptr;
newNode->next = head;
if (head != nullptr) {
head->prev = newNode;
}
head = newNode;
}
// 在链表尾部插入节点
void insertAtTail(int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = nullptr;
if (head == nullptr) {
newNode->prev = nullptr;
head = newNode;
return;
}
Node* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode;
newNode->prev = temp;
}
// 打印链表元素
void printList() {
Node* temp = head;
while (temp != nullptr) {
std::cout << temp->data << " ";
temp = temp->next;
}
std::cout << std::endl;
}
};
int main() {
DoublyLinkedList dll;
dll.insertAtHead(3);
dll.insertAtHead(2);
dll.insertAtHead(1);
dll.printList(); // 输出:1 2 3
dll.insertAtTail(4);
dll.insertAtTail(5);
dll.printList(); // 输出:1 2 3 4 5
return 0;
}
```
以上是一个简单的C++双向链表的实现示例。你可以通过调用`insertAtHead`和`insertAtTail`方法来插入节点,通过调用`printList`方法来打印链表元素。