博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
栈的应用---平衡符号
阅读量:2350 次
发布时间:2019-05-10

本文共 2732 字,大约阅读时间需要 9 分钟。

判断一行字符串输入"各种括号"是否是合法的-----------------------栈用数组实现

如:[()]是合法的(balance)

[(])是不合法的(imbalance)

#include 
#include
#include
typedef struct Mystack *Stack;struct Mystack { int Capacity; /* 栈的容量 */ int Top_of_stack; /* 栈顶下标 */ char *Array; /* 存放栈中元素的数组 */};/* 栈的创建 */Stack CreateStack(int Max){ Stack S; S = malloc(sizeof(struct Mystack)); if (S == NULL) printf("Create stack error!\n"); S->Array = malloc(sizeof(char) * Max); if (S->Array == NULL) printf("Create stack error!\n"); S->Capacity = Max; S->Top_of_stack = 0; return S;}/* 释放栈 */void DisposeStack(Stack S){ if (S != NULL) { free(S->Array); free(S); } }/* 判断一个栈是否是空栈 */int IsEmpty(Stack S){ return !S->Top_of_stack;}/* 判断一个栈是否满栈 */int IsFull(Stack S){ if (S->Top_of_stack == S->Capacity - 1) return 1; else return 0;}/* 数据入栈 */int Push(int x, Stack S){ if (IsFull(S)) printf("The Stack is full!\n"); else S->Array[S->Top_of_stack++] = x;}/* 数据出栈 */int Pop(Stack S){ if (IsEmpty(S)) printf("The Stack is empty!\n"); else S->Top_of_stack--;}/* 将栈顶返回 */char Top(Stack S){ if (!IsEmpty(S)) return S->Array[S->Top_of_stack-1]; printf("The Stack is empty!\n"); return 0;}int main(){ int i, len; char str[100]; printf("Please input the symbol that you want to balance: \n"); scanf("%s", str); len = strlen(str); /* 根据序列的长度来创建栈 */ struct Mystack *my_stack = CreateStack(len+1); for (i = 0; i < len; i++) { if (str[i] == '{' || str[i] == '[' || str[i] == '(' ) Push(str[i], my_stack); if (str[i] == '}') { if (Top(my_stack) == '{') Pop(my_stack); else break; } else if (str[i] == ']') { if (Top(my_stack) == '[') Pop(my_stack); else break; } else if (str[i] == ')') { if (Top(my_stack) == '(') Pop(my_stack); else break; } } /* 如果最后占空则序列是合法的 */ if(IsEmpty(my_stack)) printf("The symbol that you input is balance!\n"); else printf("The symbol that you input is imbalance!\n"); DisposeStack(my_stack); return 0;}

测试:

shang@shang:~/C$ ./a.out Please input the symbol that you want to balance: {[]}The symbol that you input is balance!shang@shang:~/C$ ./a.out Please input the symbol that you want to balance: [(])The symbol that you input is imbalance!shang@shang:~/C$ ./a.out Please input the symbol that you want to balance: ([{}])The symbol that you input is balance!shang@shang:~/C$

转载地址:http://zphvb.baihongyu.com/

你可能感兴趣的文章
堆栈中的EIP EBP ESP
查看>>
ESP和EBP指针寄存器
查看>>
EIP & EBP & ESP
查看>>
动态链接库(DLL)入口/出口点
查看>>
C/C++ 开发库 | C/C++ Development Library
查看>>
VC 运行时库中的 new/delete 函数
查看>>
面向对象设计原则、模式开篇
查看>>
01.单例模式--Singleton
查看>>
02.工厂模式--Factory
查看>>
03.抽象工厂模式--AbstractFactory
查看>>
04.C++反射的实现
查看>>
05.抽象工厂模式+反射--AbstractFactory&Reflect
查看>>
UML类图
查看>>
06.建造者模式--Builder
查看>>
07.原型模式--Prototype
查看>>
08.桥接模式--Bridge
查看>>
09.适配器模式--Adapter
查看>>
10.装饰模式--Decorator
查看>>
11.组合模式--Composite
查看>>
12.轻量模式--Flyweight
查看>>