求大佬帮我看看我设计的栈有什么问题
程序要求是读取用户输入的字符串,将字符串的字符逐个压入栈,然后从栈中弹出这些字符,即为该字符串的逆序。我仿照课本的链表设计了一个栈,想法是这样的,node节点记录当前字符,上一个node的地址以及下一个node的地址。stack记录链表的开头和结尾,以及项数。
程序在读取字符到栈中没问题,但是在弹出栈时,弹出字符串的最后一个字符就终止程序了。不知道自己的程序有什么问题,求大佬指教。
程序代码:
//头文件 #ifndef _STACK_H_ #define _STACK_H_ #include <stdbool.h> typedef char Item; typedef struct node { Item item; struct node * next; struct node * prev; } Node; typedef struct stack { Node * front; Node * rear; int items; } Stack; void InitializeStack(Stack * ps); bool StackIsFull( const Stack * ps); bool StackIsEmpty(const Stack * ps); int StackItemCount(const Stack * ps); bool EnStack(Item item, Stack * ps); bool Destack(Item *item, Stack * ps); void EmptyTheStack(Stack * ps); #endif
程序代码:
//实现程序 #include <stdio.h> #include <stdlib.h> #include "stack.h" void InitializeStack(Stack * ps) { ps->front = NULL; ps->rear = NULL; ps->items = 0; } bool StackIsFull( const Stack * ps) { Node * pt; pt = (Node*)malloc(sizeof(Node)); if(pt == NULL) { return true; } else { return false; } free(pt); } bool StackIsEmpty(const Stack * ps) { return ps->items == 0; } int StackItemCount(const Stack * ps) { return ps->items; } bool EnStack(Item item, Stack * ps) { Node * pnew; if(StackIsFull(ps)) return false; pnew = (Node*)malloc(sizeof(Node)); if(pnew == NULL) { fprintf(stderr, "Unable to allocate memory!\n"); exit(1); } pnew->item = item; pnew->next = NULL; if(StackIsEmpty(ps)) { pnew->prev = NULL; ps->front = pnew; ps->rear = pnew; } else { ps->rear->next = pnew; ps->rear->prev = ps->rear; } ps->rear = pnew; ps->items++; return true; } bool DeStack(Item *item, Stack * ps) { Node * pt; if(StackIsEmpty(ps)) return false; *item = ps->rear->item; pt = ps->rear; ps->rear = ps->rear->prev; free(pt); ps->items--; if(ps->items == 0) ps->rear = NULL; return true; } void EmptyTheStack(Stack * ps) { ps->items = 0; }
程序代码:
//测试程序 #include <stdio.h> #include <string.h> #include "stack.h" int main(void) { char st[256]; char temp; int i; Stack stch; puts("请输入一个字符串"); gets(st); InitializeStack(&stch); for(i = 0; i < strlen(st); i++) { if(!StackIsFull(&stch)) { temp = st[i]; EnStack(temp, &stch); } } printf("%d\n", StackItemCount(&stch)); while(!StackIsEmpty(&stch)) { DeStack(&temp, &stch); putchar(temp); } putchar('\n'); EmptyTheStack(&stch); return 0; }
[此贴子已经被作者于2018-9-30 11:07编辑过]