用 C 语言编写一个程序来生成如下所示的双向链表。首先,创建中间节点(即值为“R”)。接下来,要求用户输入以下节点(向左或向右方向)以及要存储的值。最后,从左到右显示每个节点的值。H int :您可以在该程序中声明三个指针。用 C 语言编写一个程序来生成如下所示的双向链表。首先,创建中间节点(即值为“R”)。接下来,要求用户输入以下节点(向左或向右方向)以及要存储的值。最后,从左到右显示每个节点的值。H int :您可以在该程序中声明三个指针。(要求用户可以多次输入,创建多个新节点)
时间: 2024-04-10 17:26:42 浏览: 6
下面是根据您的要求编写的一个程序,可以生成双向链表,并按顺序打印出每个节点的值:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义双向链表节点结构
struct Node {
char data;
struct Node* prev;
struct Node* next;
};
int main() {
// 创建中间节点
struct Node* middleNode = (struct Node*)malloc(sizeof(struct Node));
middleNode->data = 'R';
middleNode->prev = NULL;
middleNode->next = NULL;
// 用于指向当前节点的指针
struct Node* current = middleNode;
char direction;
char value;
// 询问用户输入节点和值
while (1) {
printf("Enter direction (L/R) and value (enter 'Q' to quit): ");
scanf(" %c", &direction);
// 检查用户是否输入 'Q',如果是则退出循环
if (direction == 'Q') {
break;
}
scanf(" %c", &value);
// 创建新节点
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->prev = NULL;
newNode->next = NULL;
// 根据用户输入的方向链接新节点到当前节点
if (direction == 'L') {
current->prev = newNode;
newNode->next = current;
// 更新当前节点指针为新节点
current = newNode;
} else if (direction == 'R') {
current->next = newNode;
newNode->prev = current;
// 更新当前节点指针为新节点
current = newNode;
} else {
printf("Invalid direction. Please enter 'L' or 'R'.\n");
}
}
// 从左到右显示每个节点的值
printf("Values from left to right: ");
struct Node* temp = middleNode;
while (temp != NULL) {
printf("%c ", temp->data);
temp = temp->next;
}
// 释放内存
temp = middleNode;
while (temp != NULL) {
struct Node* nextNode = temp->next;
free(temp);
temp = nextNode;
}
return 0;
}
```
这个程序首先创建了一个中间节点,然后要求用户输入节点的方向(向左或向右)以及要存储的值。用户可以多次输入,创建多个新节点。最后,程序会按顺序打印出每个节点的值。
请注意,在此程序中,我们使用了两个指针来遍历链表:一个指向当前节点(`current`),另一个用于打印节点值(`temp`)。在程序结束时,我们还释放了动态分配的内存,以避免内存泄漏。