输入一个整数,创建一个双向链表进行存储。这些整数从第二个开始递增。试用c++编写程序
时间: 2024-04-29 14:24:39 浏览: 12
好的,我可以回答这个问题。以下是 C 语言的代码示例:
```
#include <stdio.h>
#include <stdlib.h>
// 定义双向链表结构体
struct ListNode {
int val;
struct ListNode *prev;
struct ListNode *next;
};
int main() {
int n;
printf("请输入节点数:");
scanf("%d", &n);
// 创建链表头节点
struct ListNode *head = (struct ListNode *) malloc(sizeof(struct ListNode));
head->val = 0;
head->prev = NULL;
head->next = NULL;
// 创建链表节点并插入链表中
for (int i = 2; i <= n; i++) {
struct ListNode *node = (struct ListNode *) malloc(sizeof(struct ListNode));
node->val = i;
node->prev = head;
node->next = head->next;
head->next = node;
}
// 遍历链表并打印节点值
printf("链表节点值为:");
struct ListNode *cur = head->next;
while (cur != NULL) {
printf("%d ", cur->val);
cur = cur->next;
}
printf("\n");
// 释放链表节点和头节点的内存
cur = head->next;
while (cur != NULL) {
struct ListNode *next = cur->next;
free(cur);
cur = next;
}
free(head);
return 0;
}
```
希望能够帮助您!接下来,请问您还有什么问题需要我回答吗?