本周老師作業留了兩個。先上傳一個吧。那個有時間我再傳上來~
本周的要求:
1.給出順序棧的存儲結構定義。
2.完成順序棧的基本操作函數。
1) 初始化順序棧
2) 實現入棧和出棧操作
3) 實現取棧頂元素和判空操作
括號匹配問題
3.編寫主函數實現基本操作函數功能,並設置測試數據,測試合法和非法數據的輸出結果。
4.程序調試運行並保存輸出結果。
5.整理並提交實驗作業。
#include <cstdio>
#include <cstring>
#define Stack_Size 50
typedef struct
{
char a[Stack_Size];
int top;
}SeqStack;
int IsEmpty(SeqStack *S)//棧判空
{
return S->top == -1;
}
int Match(char ch1,char ch2)//字符串匹配
{
switch(ch2){
case ')':
if(ch1=='(')
return 1;
break;
case '}':
if(ch1=='{')
return 1;
break;
case ']':
if(ch1=='[')
return 1;
break;
}
return 0;
}
void InitStack(SeqStack * S)//初始化順序棧
{
S->top = -1;
}
void Push(SeqStack * S,char x)//進棧
{
S->top++;
S->a[S->top]=x;
}
void Pop(SeqStack * S,char *x)//出棧
{
*x=S->a[S->top];
S->top--;
}
void GetTop(SeqStack * S,char *x)
{
*x=S->a[S->top];
}
void BracketMatch(char *str)
{
SeqStack S;
char ch;
InitStack(&S);
for(int i=0;str[i]!='\0';i++)
{
switch(str[i]){
case '(':
case'[':
case'{':
Push(&S,str[i]);
break;
case ')':
case']':
case'}':
if(IsEmpty(&S)){
printf("\n右括號多余!\n");
return ;
}
else{
GetTop(&S,&ch);
if(Match(ch,str[i]))
Pop(&S,&ch);
else{
printf("\n 對應的左右括號不同類!\n");
return ;
}
}
}
}
if(IsEmpty(&S))
printf("\n括號匹配!\n");
else
printf("\n左括號多余!\n");
}
int main()
{
char strr[50];
printf("請輸入各種括號\n");
gets(strr);
BracketMatch(strr);
return 0;
}
