栈的应用---平衡符号
来源:互联网 发布:php正则表达式函数 编辑:程序博客网 时间:2024/05/12 15:41
判断一行字符串输入"各种括号"是否是合法的-----------------------栈用数组实现
如:[()]是合法的(balance)
[(])是不合法的(imbalance)
#include <stdio.h>#include <stdlib.h>#include <string.h>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$
- 栈的应用---平衡符号
- 栈的应用--平衡符号
- 栈的应用---平衡符号
- 栈的应用----平衡符号
- 栈的应用---平衡符号的检测
- 栈的应用之平衡符号
- 栈的应用-平衡符号(C版)
- 栈的应用——平衡符号
- 栈的应用:平衡符号问题
- 栈的应用 — 平衡符号
- javascript栈的应用之符号平衡
- 栈的应用 - 符号平衡问题
- Java栈的应用检测平衡符号
- 栈的应用—平衡符号
- 栈的应用之检测平衡符号
- 栈的应用之平衡符号
- 栈应用—平衡符号
- 平衡符号(栈应用一)
- 【Orientation】详解Android中的屏幕方向
- Android Styles / Themes要点整理
- 转载————————---多态--------------
- oracle 统计信息是什么
- Combinations
- 栈的应用---平衡符号
- 日语N2模拟题
- JButton常用设置
- SAP 表格维护生成器-部分字段不能修改或不能看见
- 怎么用程序实现调用Android手机的拍照功能
- windows 检测串口概念 参考
- Kobject、Kset 和 Subsystem
- 2012年12月日语 N2
- linux下vim配置