C语言双向链表实现栈存储字符时输入及节点创建问题求助
双向链表实现栈的问题修复
问题根因说明
- 输入异常问题:
scanf("%c")会读取输入缓冲区残留的换行符,导致第二次读取val时直接拿到换行,无法捕获用户输入的控制字符。只需在%c前加空格即可过滤所有前置空白字符(换行、空格、制表符等)。 - 栈构建失败问题:
create_Node函数中malloc申请内存后缺少空指针判断,直接无条件返回内存分配失败,后续节点初始化、节点关联逻辑完全未执行,补充空指针判断分支即可修复。 - 显示异常问题:
display函数使用%d格式符输出字符,会打印字符对应的ASCII码而非实际字符,改为%c即可。
修正后完整代码
#include<stdio.h> #include<stdlib.h> typedef struct Node Node; struct Node{ Node *prev; int ch; Node *next; }; typedef enum SIGNAL SIGNAL; enum SIGNAL {MEMORY_CREATION_FAILED, SUCCESS, FAILED, UNDERFLOW, OVERFLOW}; // 函数声明 SIGNAL create_Node(Node **top, char c); void display(Node *q); // 主函数 int main(){ Node *top = NULL; char c, val=9; while (1){ printf("\nEnter character to insert in string :"); // 加空格过滤前置空白字符 scanf(" %c",&c); create_Node(&top, c); printf("\nPress ';' to exit or any key to continue : "); // 加空格过滤前置空白字符 scanf(" %c",&val); if(val == ';'){ printf("\nexiting...\n"); display(top); return 0; } } return 0; } // 创建节点并插入栈的函数 SIGNAL create_Node(Node **top, char c){ Node *tem = (Node*)malloc(sizeof(Node)); // 补充malloc失败的判断分支 if (tem == NULL) return MEMORY_CREATION_FAILED; tem->ch = c; tem->next = tem->prev = NULL; if(*top != NULL){ (*top)->next = tem; tem->prev = *top; } *top = tem; return SUCCESS; } // 显示栈内容函数 void display(Node *q){ if(q == NULL){ printf("\nString is empty nothing to display"); return; } printf("String is :\n"); for(; q != NULL ; q = q->prev) // 改为%c输出字符 printf("%c",q->ch); }
内容的提问来源于stack exchange,提问作者user16790490
相关产品推荐
相关产品推荐

