数据结构--利用栈实现括号匹配

/*下午打球去了,虐菜了*/

 <pre name="code" class="cpp">#ifndef _MATCH_H_
#define _MATCH_H_  

#include<iostream>
#include<string.h>
#include<assert.h>
using namespace std;

typedef char ElemType;
#define STACK_INIT_SIZE 50 

typedef struct Stack
{
    ElemType *base;
    int top;
    int stacksize;
    int capacity;
}Stack;

void InitStack(Stack *st);
bool IsEmpty(Stack *st);
bool IsFull(Stack *st);
bool Push(Stack *st,ElemType x);
bool Pop(Stack *st);
//ElemType GetTop(Stack *st,ElemType *x);
 ElemType GetTop(Stack *stack);
#endif   
#include"match.h"

void InitStack(Stack *st)
{
    st->base = (ElemType *)malloc(sizeof(ElemType)*STACK_INIT_SIZE);
    assert(st->base != NULL);
    st->capacity = STACK_INIT_SIZE;
    st->top = 0;
}
bool IsFull(Stack *st)
{
    return st->top >= st->capacity;
}  

bool IsEmpty(Stack *st)
{
    return st->top == 0;
}
bool Push(Stack *st, ElemType x)
{
    if(IsFull(st))
    {
        cout<<"栈已满,"<<x<<"不能入栈!"<<endl;
        return false;
    }
    st->base[st->top++] = x;
    return true;
}  

bool Pop(Stack *st)
{
    if(IsEmpty(st))
    {
        cout<<"栈已空,不能出栈!"<<endl;
        return false;
    }  

    st->top--;
    return true;
}  

/*ElemType GetTop(Stack *st,ElemType *x)
{
    if(IsEmpty(st))
    {
        cout<<"栈为空:"<<endl;
        return false;
    }
    *x = st->base[--st->top];//   *x = st->base[st->top--]; 效果是一样的吗?
   // cout<<"栈顶是:"<<*x<<endl;//不必要的输出
    return *x;
}  */
ElemType GetTop(Stack *stack)
{
    if(IsEmpty(stack))
    {
        cout<<"栈空!"<<endl;
    }
    return stack->base[stack->top-1];
}
#include"match.h"

void main()
{
	Stack st;
	char str[1000];
	ElemType item;
	InitStack(&st);
    cin>>str;
    //[]
	int len = strlen(str);

	int i = 0;
	int flag = 1;
	while(i < len)
	{
		if(str[i] == '[' || str[i] == '(' || str[i] == '{')
			Push(&st,str[i]);
		else if(str[i] == ']')
		{
		//	if(IsEmpty(&st)||GetTop(&st, &item) != '[')
			if(IsEmpty(&st)||GetTop(&st ) != '[')
				flag = 0;
			else
				Pop(&st);
		}
		else if(str[i] == ')')
		{
		//	if(IsEmpty(&st)||GetTop(&st,&item) != '(')
			if(IsEmpty(&st)||GetTop(&st ) != '(')
				flag = 0;
			else
				Pop(&st);
		}
		else if(str[i] == '}')
		{
			//if(IsEmpty(&st)||GetTop(&st, &item) != '{')
			if(IsEmpty(&st)||GetTop(&st ) != '{')
				flag = 0;
			else
				Pop(&st);
		}
		i++;
	}

if(!IsEmpty(&st))
    {
        flag = 0;
    }
    if(flag == 1)
        cout<<" 括号匹配 "<<endl;
    else
    {
        cout<< "括号不匹配"<<endl;
    }
} 

<img src="http://img.blog.csdn.net/20150516005559696?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZnVqaW5sb25nNTIw/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />

				
时间: 2024-10-10 15:22:13

数据结构--利用栈实现括号匹配的相关文章

第一篇博客——利用“栈”进行括号匹配的算法

bool BracketsCheck(char *str){ InitStack(S); int i=0; while(str[i]!='\0'){ switch(str[i]){ case'(':Push(S,str[i]);break; case'[':Push(S,str[i]);break; case'{':Push(S,str[i]);break; case')': Pop(S,e); if(e!='(')return false; break; case']': Pop(S,e);

(编程训练)再回首,数据结构——(升级版)使用栈判断括号匹配

点击打开 基础版 最近在复习数据结构,顺便看看大一的时候写的代码,看完之后比当初有了更加深刻的体会. 希望这些能提供给初学者一些参考. 在VC++6.0下可运行,当初还写了不少注释. /* ********************************************************** * 3-2 * 设在一个算术表达式中允许使用3种括号:圆括号"(".")",方 * 括号"["."]",花括号"

imooc数据结构探险-栈篇 栈应用括号匹配二 由群友启发改良james_yuan老师算法

如图所示 引用群友内容 //老师代码有点麻烦了,不用声明两个mystack的,直接判断是否是左括号, //是的话就在mystack中push另一半括号:如果是右括号且又不是需要的括号, //就直接打印不匹配,如果是需要的右括号,就pop掉左括号.最后看mystack中栈顶是否为0,为0则打印括号匹配 /* 老师最后一点其实错了,default 其实没有必要写,只要把pNeedStack->pop(currentNeed)改为 if(!pNeedStack->pop(currentNeed))

Python 用栈判断括号匹配

#!/usr/bin/python # -*- coding: UTF-8 -*- from pythonds.basic.stack import Stack def parChecker(symbolString): s = Stack() balanced = True index = 0 while index < len(symbolString) and balanced: symbol =symbolString[index] #左边括号入栈 if symbol == '(': s

C++,利用链式栈实现括号匹配,界面友好,操作方便,运行流畅

#include<iostream> #include<string> using namespace std; struct Node { char ch; Node* next; Node(char c, Node* p){ ch = c; next = p; } }; void main() { string str; bool flag = true; while (flag) { cout << "请输入算术表达式:" << e

栈之括号匹配

#include<stdio.h> #include<string.h> #define MaxSize 100 void ExpIsCorrect(char exp[],int n); typedef char DataType; typedef struct { DataType stack[MaxSize]; int top; }SeqStack; void StackInitiate(SeqStack *s)//初始化 { s->top=0; } int StackN

JAVA栈实例—括号匹配

1 import java.util.Stack; 2 3 public class test { 4 public static void main(String[] args){ 5 System.out.print(isStringBalanced("asdasd)d")); 6 } 7 8 public static boolean isStringBalanced(String string){ 9 final char openrb = '('; //定义常量 10 fin

栈(括号匹配)

假设一个算术表达式中可以包含三种括号:圆括号"("和")",方括号"["和"]"和花括号"{"和" ",且这三种括号可按任意的次序嵌套使用(如:-[-{- -[-]-]-[-]-(-)-).编写判别给定表达式中所含括号是否正确配对出现的算法.输出结果YES 或者 NO. Input 5+{[2X5]+2} Output YES Sample Input 8-[{2+7]} Sample

20. Valid Parentheses(用栈实现括号匹配)

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct