数据结构实验之栈与队列四:括号匹配
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
给你一串字符,不超过50个字符,可能包括括号、数字、字母、标点符号、空格,你的任务是检查这一串字符中的( ) ,[ ],{ }是否匹配。
Input
输入数据有多组,处理到文件结束。
Output
如果匹配就输出“yes”,不匹配输出“no”
Sample Input
sin(20+10)
{[}]
Sample Output
yes
no
Hint
Source
ma6174
我是打算用链栈写的,无奈水平不够,先贴上错的但是费劲写的代码,以便后期修改
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef char ElementType;
typedef struct node
{
ElementType Data;
struct node *next;
} LinkStack;
LinkStack *createStack(LinkStack *S)
{
S = (LinkStack *)malloc(sizeof(struct node));
S->next = NULL;
return S;
}
int IsEmpty(LinkStack *S)
{
return(S->next == NULL);
}
void Push(ElementType item,LinkStack *S)
{
struct node *TemCell;
TemCell = (LinkStack *)malloc(sizeof(LinkStack));
TemCell->Data = item;
TemCell->next = S->next;
S->next = TemCell;
}
char GetTop(LinkStack *S)
{
if(!S)
return 0;
else
{
return S->Data;
}
}
int Pop(LinkStack *S)
{
struct node *FirstCell;
ElementType TopElem;
if(IsEmpty(S))
{
return -1;
}
else
{
FirstCell = S->next;
S->next =FirstCell->next;
TopElem = FirstCell->Data;
free(FirstCell);
return TopElem;
}
}
int main()
{
int i,length;
char a[55],e;
while(gets(a))
{
int flag = 1;
LinkStack S;
createStack(&S);
length = strlen(a);
for(i = 0; i < length; i++)
{
if(a[i] == '{' || a[i] == '[' || a[i] == '(')
{
Push(a[i],&S);
}
else if(a[i] == '}' || a[i] == ']' || a[i] == ')')
{
if(!IsEmpty(&S))
{
flag = 0;
break;
}
else
{
e =GetTop(&S);
if((a[i] == '}' && e == '{')||(a[i] == ']' && e == '[')||(a[i] == ')' && e == '('))
{
Pop(&S);
}
}
}
}
if(!flag)
{
printf("no\n");
}
else if(IsEmpty(&S))
{
printf("yes\n");
}
else
{
printf("no\n");
}
}
return 0;
}
问题有好多....目前水平真的不够。。。。。我还是用数组写吧~
我回来了~~~
数组版
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i,j,flag,length;
char a[55],b[55];
while(gets(a))
{
length = strlen(a);
flag = 1;j = 1;
for(i = 0; i< length; i++)
{
if(a[i] == '{' || a[i] == '[' || a[i] == '(')
{
b[j] = a[i];
j++;
}
if(a[i] == '}' || a[i] == ']' || a[i] == ')')
{
if(j == 1)
{
flag = 0;
break;
}
else
{
if((a[i] == '}' && b[j-1] == '{')|| (a[i] == ']' && b[j-1] == '[') ||(a[i] == ')' && b[j-1] == '('))
{
b[j - 1] = 0;
j--;
}
else
{
b[j] = a[i];
j++;
}
}
}
}
if(!flag)
{
printf("no\n");
}
else
{
if(j==1&&b[1] == 0)
printf("yes\n");
else printf("no\n");
}
}
return 0;
}
用的栈的思路,做的~上面的代码什么时候我闲的没事我会试着写一写~