用c++写一个双向链表
时间: 2023-04-09 17:00:26 浏览: 110
好的,我可以回答这个问题。以下是一个用 C 语言实现的双向链表的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
struct Node* head = NULL;
void insertAtBeginning(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = head;
if (head != NULL) {
head->prev = newNode;
}
head = newNode;
}
void insertAtEnd(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
newNode->prev = NULL;
head = newNode;
return;
}
struct Node* lastNode = head;
while (lastNode->next != NULL) {
lastNode = lastNode->next;
}
lastNode->next = newNode;
newNode->prev = lastNode;
}
void printList() {
struct Node* currentNode = head;
printf("List: ");
while (currentNode != NULL) {
printf("%d ", currentNode->data);
currentNode = currentNode->next;
}
printf("\n");
}
int main() {
insertAtEnd(1);
insertAtBeginning(2);
insertAtEnd(3);
insertAtBeginning(4);
printList();
return 0;
}
```
这个程序实现了双向链表的插入和打印功能。在 `main` 函数中,我们先在链表末尾插入了一个元素 1,然后在链表开头插入了元素 2,再在末尾插入了元素 3,最后在开头插入了元素 4。最终打印出链表的内容为:4 2 1 3。
阅读全文