#include <stdio.h>
#include <stdlib.h>
typedef struct SymbolStack
{
int symbol;
struct SymbolStack *next;
}*pstack;
typedef struct SymbolStack stack;
int IsEmpty(pstack s)
{
return s->next == NULL;
}
pstack CreateRoot(void)
{
pstack root;
root = (pstack)malloc(sizeof(stack));
root->next = NULL;
return root;
}
void push(char c, pstack root)
{
pstack s;
s = (pstack)malloc(sizeof(stack));
s->next = root->next;
s->symbol = c;
root->next = s;
}
void pop(pstack root)
{
pstack tmpcell;
tmpcell = root->next;
if (tmpcell == NULL)
{
printf("Error!");
return;
}
root->next = tmpcell->next;
free(tmpcell);
}
char top(pstack root)
{
if (root->next == NULL)
return 0;
else return root->next->symbol;
}
void BalancingSymbol(void)
{
char c;
pstack root = CreateRoot();
pstack s;
while ((c = getchar()) != EOF)
{
/*if anything open*/
if (c == '(' || c == '{' || c == '[')
{
push(c, root);
putchar(c);
}
/*if anything close*/
else
if (c == ')')
{
if (top(root) == c - 1)
{
pop(root);
putchar(c);
}
else printf("error ");
}
else
if (c == '}' || c == ']')
{
if (top(root) == c - 2)
{
pop(root);
putchar(c);
}
else printf("error ");
}
else putchar(c);
}
/*if at the end of file*/
if (!IsEmpty(root))
printf("error\n");
}
Make an empty stack. Read characters until end of file. If the character is an opnening symbol, push it onto the stack. If it is a closing symbol, then if the stack is empty report an error. Otherwise, pop the stack. If the symbol popped is not the corresponding opnening symbol, then report an error. At the end of file, if the stack is not empty report an error.