#include <stdio.h>
#include <stdlib.h>
typedef char ElemType;
struct SNode
{
ElemType Element;
struct SNode* Next;
};
typedef struct SNode *Stack;
Stack CreateStack()
{
Stack S;
S=(Stack)malloc(sizeof(struct SNode));
S->Next = NULL;
return S;
}
int IsEmpty(Stack S)
{
return (S->Next == NULL);
}
void Push(ElemType item,Stack S)
{
struct SNode * TmpCell;
TmpCell = (struct SNode*)malloc(sizeof(struct SNode));
TmpCell->Element = item;
TmpCell->Next = S->Next;
S->Next = TmpCell;
}
ElemType Pop(Stack S)
{
struct SNode *FirstCell;
ElemType TopElem;
if (IsEmpty(S)) {
return -1;
}else{
FirstCell = S->Next;
S->Next = FirstCell->Next;
TopElem = FirstCell->Element;
free(FirstCell);
return TopElem;
}
}
ElemType GetTop(Stack S)
{
ElemType TopElem;
if (IsEmpty(S)) {
return -1;
}else{
TopElem = S->Next->Element;
return TopElem;
}
}
ElemType Reverse(ElemType a)
{
ElemType R = '0';
switch(a)
{
case '(':R = ')';break;
case '[':R = ']';break;
case '{':R = '}';break;
default:break;
}
return R;
}
void check(Stack S)
{
struct SNode *temp;
int flag[3] = {0,0,0};
int flaga = 0;
if (IsEmpty(S))
{
printf("0");
}
else{
temp = S->Next;
while(temp)
{
switch (temp->Element)
{
case '(':
case ')':flag[0] = 1;flaga = 1;break;
case '[':
case ']':flag[1] = 2;flaga = 1;break;
case '{':
case '}':flag[2] = 3;flaga = 1;break;
default:break;
}
temp = temp->Next;
}
if (flaga == 0){
printf("0");
return;
}
for (int i = 0; i < 3; i++)
{
if (flag[i] > 0){
printf("%d,",flag[i]);
}
}
}
}
int main()
{
Stack S;
S=CreateStack();
char c[60] = {0};
gets(c);
for (int i = 0; i <= 50; i++){
if (c[i] == '(' || c[i] == '{' || c[i] == '['){
Push(c[i],S);
}
else if (c[i] == ')' || c[i] == '}' || c[i] == ']'){
if (c[i]==Reverse(GetTop(S)))
Pop(S);
else
Push(c[i],S);
}
}
check(S);
return 0;
}
感谢dzh给我改的漂亮代码让我终于通过OJ
、