`

栈练习一

 
阅读更多

题目:从文件中读取表达式,对其中的“()”“{}”“【】”括号匹配,输出匹配的结果

#include<iostream>
#include<fstream>
#include<malloc.h>
#include<string>
using namespace std;
typedef char SElemType;
typedef int Status;

#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -1


 #define STACK_INIT_SIZE 10//初始分配量
 #define STACKINCREMENT 2 //存储空间分配增量

 typedef struct SqStack
 {
   SElemType *base; //在栈构造之前和销毁之后,base值为NULL
   SElemType *top; //栈顶指针
   int stacksize; //当前已分配的存储空间,以元素为单位
 }SqStack; //顺序栈

  Status InitStack(SqStack *S,int size)
 { /* 初始栈 */
   (*S).base=(SElemType *)malloc(size*sizeof(SElemType));
   if(!(*S).base)
     exit(OVERFLOW); 
   (*S).top=(*S).base;
   (*S).stacksize=size;
   return OK;
 }

 Status StackEmpty(SqStack S)
 { /* 判断栈空 */
   if(S.top==S.base)
     return TRUE;
   else
     return FALSE;
 }
  
 Status 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;
 }

 Status Pop(SqStack *S,SElemType *e)
 { /* 出栈 */
   if((*S).top==(*S).base)
     return ERROR;
   *e=*--(*S).top;
   return OK;
 }


 void check(char a[],int size)
 { 
   SqStack s;
   SElemType *p,e;
   if(InitStack(&s,size)) 
   {
     
    
     p=a;
	  
     while(*p!=NULL) 
	 {
		// cout<<*p<<endl;
       switch(*p)
       {
	    case '{':
         case '(':
         case '[':Push(&s,*p++);
			
                  break; 
		 case '}':
         case ')':
         case ']':if(!StackEmpty(s)) 
                  {
                    Pop(&s,&e); 
                    if(*p==')'&&e!='('||*p==']'&&e!='[') 
                    {
                      cout<<("左右括号不配对\n");
                      exit(ERROR);
                    }
                    else
                    {
                      p++;
                      break; 
                    }
                  }
                  else 
                  {
                    cout<<("缺乏左括号\n");
                    exit(ERROR);
                  }
         default: p++; 
       }
	 }
       if(StackEmpty(s)) 
         cout<<("括号匹配\n");
       else
         cout<<("缺乏右括号\n");
   }
 }
void StrToChar(char a[],string b)
{

	
  for(int i=0;i<b.length();i++)
  {
     a[i]=b[i];
	 
	 cout<<a[i];
  }
  a[b.length()]='\0';
  cout<<endl;
}
 void main()
 {
   string str[2];
   ifstream infile;
   char a[256];
   int k=0;
   int size;
   infile.open("input.txt");
    infile>>size;

	while(infile.good() &&k<2)
	{

	  getline(infile,str[k]);
	  k++;
	}
  infile.close();
  cout<<"表达式是:";
	StrToChar(a,str[1]);
   check(a,size);

 }


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics