# 利用栈实现括号配对

#ifndef _SEQSTACK_
#define _SEQSTACK_
#endif
#include "stdio.h"
#include "math.h"

typedef struct
{
DataType stack [MaxSize];

int top;

int count;

} SeqStack;

void StackInitiate (SeqStack *S)

{

S->top =0;
}

int StackNotEmpty(SeqStack S)
{

if (S.top<=0)
{

printf ("\n\nThis Stack is empty !");

return 0;
}

else  return 1;
}

int StackPush (SeqStack *S ,DataType x)
{

if (S->top>=MaxSize)

{
printf ("The stack is full !");

return 0;
}

else

{

S->stack[S->top]=x;

S->top++;

S->count++;

return 1;

}
}

int StackPop(SeqStack *S,DataType *d)

{

if (S->top<=0)

{
printf ("There is no element to pop !");

return 0;
}

else

{

S->top--;    //if stack is empty ,you should make sure that the value of "S->top" is 0

*d=S->stack[S->top];  //this "stack[]" array should be popped begin with "stack[9]" not stack[10],so we should reduce 1 befor we execute the algorithm  in this line

// printf ("%d",S->top);

//S->top--;

S->count--;

return 1;

}
}

int StackTop(SeqStack S,DataType *d)

{

if (S.top<=0)
{

//printf (" This stack is empty !");

return 0;
}

else
{

*d=S.stack[S.top-1];

return 1;

}

}

#include <stdio.h>

#define MaxSize 100

typedef char DataType ;

#include "SeqStack.h"

void main ()

{

char a[MaxSize];

int i,n;

char p,x,s;

SeqStack MyStack;

StackInitiate(&MyStack);

//StackTop(MyStack,&x);

scanf ("%d",&n);

for (i=0;i<n+2;i++)
{

scanf ("%c",&a[i]);

if (a[i]=='('||a[i]=='<'||a[i]=='[')
{

StackPush(&MyStack,a[i]);
}
else    if (a[i]=='>'&&(StackTop(MyStack,&x))&&(x=='<'))
{

StackPop(&MyStack,&p);

}
else    if (a[i]=='>'&&(StackTop(MyStack,&x))&&(x!='<'))
{
printf ("\n wrong \n");
return ;

}
else    if (a[i]==')'&&(StackTop(MyStack,&x))&&(x=='('))
{

StackPop(&MyStack,&p);

}
else    if (a[i]==')'&&(StackTop(MyStack,&x))&&(x!='('))
{

printf ("\n wrong \n");
return ;

}

else if ((a[i]==']')&&(StackTop(MyStack,&x))&&(x=='['))
{

StackPop(&MyStack,&p);

}
else if ((a[i]==']')&&(StackTop(MyStack,&x))&&(x!='['))
{

printf ("\n wrong \n");

return ;

}
else if (n%2!=0)
{

printf ("\n wrong \n");

return ;

}
}

if (StackNotEmpty(MyStack))
{

printf ("\nThis array of character can not make a pair!\n");

StackTop(MyStack,&p);

printf ("%c",p);

//    printf ("\n%d\n",MyStack.count);

}

else

printf ("\nThis array of character can make a pair!\n");

}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120