*Copyright (c)2017, School of computer and control engineering, Yantai University
*All rights reservrd.
*Author: Li Xinhao
*Completion time: December 14, 2017
*Version number: v1.0
*Problem Description: suppose three kinds of parentheses are allowed in an expression: parentheses, square brackets, and braces. Write an algorithm to determine whether the various left parentheses in the expression match the right parentheses.
For example, input 2 + (3 + 4) * 2 + {[3]} - 8, output matching is correct; input 2 + (3 + 4 * [2) + {[3]} - 8, output matching is wrong.
1, Create a new project to create a header file based on the sequence stack database:
#ifndef SQSTACK_H_INCLUDED #define SQSTACK_H_INCLUDED #define MaxSize 100 typedef char ElemType; typedef struct { ElemType data[MaxSize]; int top; //Stack pointer } SqStack; //Sequence stack type definition void InitStack(SqStack *&s); //Initialization stack void DestroyStack(SqStack *&s); //Destruction stack bool StackEmpty(SqStack *s); //Is the stack empty int StackLength(SqStack *s); //Return the number of elements in the stack -- stack length bool Push(SqStack *&s,ElemType e); //Push bool Pop(SqStack *&s,ElemType &e); //Stack out bool GetTop(SqStack *s,ElemType &e); //Data element at the top of stack void DispStack(SqStack *s); //Output stack #endif // SQSTACK_H_INCLUDED
2, Create the source file sqstack.cpp to define these functions:
#include <stdio.h> #include <malloc.h> #include "sqstack.h" void InitStack(SqStack *&s) { s=(SqStack *)malloc(sizeof(SqStack)); s->top=-1; } void DestroyStack(SqStack *&s) { free(s); } int StackLength(SqStack *s) //Return the number of elements in the stack -- stack length { return(s->top+1); } bool StackEmpty(SqStack *s) { return(s->top==-1); } bool Push(SqStack *&s,ElemType e) { if (s->top==MaxSize-1) //Stack full, i.e. stack overflow return false; s->top++; s->data[s->top]=e; return true; } bool Pop(SqStack *&s,ElemType &e) { if (s->top==-1) //When the stack is empty, i.e. overflow under the stack return false; e=s->data[s->top]; s->top--; return true; } bool GetTop(SqStack *s,ElemType &e) { if (s->top==-1) //When the stack is empty, i.e. overflow under the stack return false; e=s->data[s->top]; return true; } void DispStack(SqStack *s) //Output stack { int i; for (i=s->top;i>=0;i--) printf("%c ",s->data[i]); printf("\n"); }
3, Set up the source file main.cpp to achieve the following functions:
#include <stdio.h> #include "sqstack.h" int main() { char c; char st[50]; int d=1, i; SqStack *s; InitStack(s); printf("Please enter an expression:"); scanf("%s", st); for(i=0; st[i]!='\0'&&d; i++) { switch(st[i]) { case'(': case'[': case'{': Push(s, st[i]); break; case')': Pop(s, c); if(c!='(') d=0; break; case']': Pop(s, c); if(c!='[') d=0; break; case'}': Pop(s,c); if(c!='{') d=0; break; } } if(StackEmpty(s)&&d==1) printf("Matching correctly!!\n"); else printf("Pairing error!!\n"); return 0; }
4, The screenshot of the test results is as follows: