C++棧括號檢查
#include "SqStack.h"//該標頭檔案為自定義,程式碼如下
#include<iostream>
#include<string>
#include<stack>
#include<cstring>
using namespace std;
int main()
{
SqStack S;
InitStack(S);
char ch[100];
char e;
while(cin>>ch)
{
Push(S,ch[0]);
int length = strlen(ch);
cout<<"長度:"<<length<<endl;
if(ch[0] == ')' || ch[0] =='}' || ch[0] == ']')
{
cout<<"匹配失敗!"<<endl;
return 0;
}
else if(ch[1]=='\0')
{
cout<<"匹配失敗!"<<endl;
return 0;
}
else
{
//cout<<"vwegbr"<<endl;
for(int i = 1; i < length; ++i)
{
if(ch[i] == '(' || ch[i] == '{' || ch[i] == '[')
{
Push(S,ch[i]);
}
else if(ch[i] == ')')
{
if(!StackEmpty(S))///佇列為空
{
cout<<"匹配失敗!"<<endl;
return 0;
}
else if(*(S.top-1)!= '(')
{
cout<<"匹配失敗!"<<endl;
return 0;
}
Pop(S,e);
}
else if(ch[i] == '}')
{
if(!StackEmpty(S))///佇列為空
{
cout<<"匹配失敗!"<<endl;
return 0;
}
else if(*(S.top-1)!= '{')
{
cout<<"匹配失敗!"<<endl;
return 0;
}
Pop(S,e);
}
else if(ch[i] == ']')
{
if(!StackEmpty(S))///佇列為空
{
cout<<"匹配失敗!"<<endl;
return 0;
}
else if(*(S.top-1)!= '[')
{
cout<<"匹配失敗!"<<endl;
return 0;
}
Pop(S,e);
}
}
//cout<<StackLength(S)<<endl;
if(StackLength(S) == 0){
cout<<"匹配成功!"<<endl;
}else{
cout<<"匹配失敗"<<endl;
}
return 0;
}
}
}
SqStack.h:
#ifndef SQSTACK_H_INCLUDED
#define SQSTACK_H_INCLUDED
#include<iostream>
#include<cstdlib>
#include<malloc.h>
#include<stdio.h>
using namespace std;
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define STACK_INIT_SIZE 100///儲存空間初始分配量
#define STACKINCREMENT 10///儲存空間分配增量
typedef char SElemType;
typedef struct {
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
///建立一個空棧
void InitStack(SqStack &S){
S.base = (SElemType *) malloc(STACK_INIT_SIZE * sizeof(SElemType));
//S.base = NULL;
if(!S.base) exit(OVERFLOW);
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
}
///銷燬棧
void DestoryStack(SqStack &S){
S.top = S.base;
free(S.base);
return;
}
///清理棧
void ClearStack(SqStack &S){
S.top = S.base;
}
///判斷棧是否為空
int StackEmpty(SqStack S){
if(S.base == S.top)return FALSE;
return TRUE;
}
///返回棧的長度
int StackLength(SqStack S){
return S.top-S.base;
}
///得到棧頂元素並由e返回
int GetTop(SqStack &S,SElemType &e){
if(S.top == S.base) return ERROR;
e = *(S.top - 1);
cout<<e<<endl;
return OK;
}
///插入元素e為新的棧頂元素
int Push(SqStack &S, SElemType &e){
if(S.top - S.base >= S.stacksize){
S.base = (SElemType *)realloc
(S.base,(S.stacksize +STACKINCREMENT)*sizeof(SElemType));
if(!S.base)exit(OVERFLOW);
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top++=e;
return OK;
}
///若棧頂不空,則刪除S的棧頂元素,用e返回。並返回OK,否則返回ERROR
int Pop(SqStack &S,SElemType &e){
if(S.top == S.base) return ERROR;
e = *--S.top;
return OK;
}
///依次呼叫visit()
void StackTraverse(SqStack S,void (*visit)(SqStack S)){
visit(S);
}
void visit(SqStack S){
while(S.top!=S.base){
cout<<*--S.top<<" " ;
}
}
#endif // WANGDAO_SQSTACK_H_INCLUDED