标签:
#include<stdio.h> #include<stdlib.h> #include<malloc.h> //定义节点 struct Node { int data; struct Node *next; }; typedef Node StackNode; //定义栈 struct Stack { StackNode *top; StackNode *base; }; typedef Stack SqStack; //定义创建栈的函数 int InitStack(SqStack *S) { S->base = (StackNode*)malloc(sizeof(Node)); if (!S->base) { printf("error"); exit(1); } S->top = S->base; return 0; } //定义压栈函数 int PushStack(SqStack *S) { int e; StackNode *ps; ps = (StackNode *)malloc(sizeof(Node)); if (!ps) { printf("error"); exit(1); } printf("请输入你需要压入栈的数:"); scanf_s("%d", &e); ps->data = e; ps->next = S->top; S->top = ps; return 0; } //定义弹栈函数 int PopStack(SqStack *S) { int e; StackNode *ps; ps = S->top; S->top = S->top->next; e = ps->data; free(ps); return e; } //定义栈遍历函数 int TravelStack(SqStack *S) { StackNode *ps; ps = S->top; while (ps != S->base) { printf("数据为:%d\n", ps->data); ps = ps->next; } return 0; } //定义判断栈是否为空函数 bool EmptyStack(SqStack *S) { StackNode *ps; ps = S->top; if (ps == S->base) { return true; } else { return false; } } //定义清空栈的函数 int ClearStack(SqStack *S) { StackNode *ps; ps = S->top; while (S->top != S->base) { S->top = S->top->next; free(ps); } return 0; } //主函数 int main() { int i,dec,input,DEC; SqStack *stack; stack = new Stack; InitStack(stack); do{ printf("请选择你需要的基本操作:\n"); printf("1************往栈中加入数据\n"); printf("2************遍历该栈\n"); printf("3************清空该栈\n"); printf("4************删除栈顶元素\n"); scanf_s("%d", &i); switch (i) { case 1: { printf("是否想往栈中输入数据?是选择1/否选择2\t"); scanf_s("%d", &dec); while (dec == 1) { PushStack(stack); printf("是否继续输入数据?是选择1/否选择2\t"); scanf_s("%d", &input); dec = input; } printf("你输入的数据为:\n"); TravelStack(stack); break; } case 2: { TravelStack(stack); break; } case 3: { ClearStack(stack); if (EmptyStack(stack)) { printf("该栈已经空!"); } else { printf("该栈不为空!"); }; break; } case 4: { int ReturnData; ReturnData = PopStack(stack); break; } } printf("是否要继续?是选择1/否选择2:\t"); scanf_s("%d", &DEC); } while (DEC == 1); }
标签:
原文地址:http://www.cnblogs.com/code-wangjun/p/4356528.html