代码: 全选
// Linked Stack Example | Match Brackets
// Last Modified: 2008-06-10
// Last Modified: 2008-06-11
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
char data;
struct node *next;
} stack;
stack *init(stack *top)
{
stack *tmp;
while (top->next)
{
tmp = (stack *)malloc(sizeof(stack));
tmp = top;
top = top->next;
free(tmp);
}
printf("\n");
printf("\n\n :: init stack :: ");
return top;
}
int is_empty(stack *top, int print_msg)
{
if (top->data)
{
if (print_msg) printf("\n\n stack is not empty ");
return 0;
}
else
{
if (print_msg) printf("\n\n stack is empty ");
return 1;
}
}
void print(stack *top)
{
stack *tmp;
tmp = (stack *)malloc(sizeof(stack));
if (!is_empty(top, 0))
{
tmp = top;
printf("\n\n +---+ ");
while (tmp && tmp->data)
{
printf("\n | %c | ", tmp->data);
printf("\n +---+ ");
tmp = tmp->next;
}
}
}
stack *push(stack *top, char val)
{
stack *tmp;
tmp = (stack *)malloc(sizeof(stack));
if (!tmp)
{
printf("\n\n overflow ");
return top;
}
//if (val > 33 && val > 126)
// val = 129;
tmp->data = val;
tmp->next = top;
top = tmp;
return top;
}
stack *pop(stack *top)
{
stack *tmp;
tmp = (stack *)malloc(sizeof(stack));
if (is_empty(top, 0))
return top;
tmp = top;
top = top->next;
free(tmp);
return top;
}
char get_top(stack *top)
{
if (is_empty(top, 0))
return '\0';
return top->data;
}
int main()
{
stack *init(stack *top);
stack *push(stack *top, char val);
stack *pop(stack *top);
char get_top(stack *top);
int is_empty(stack *top, int print_msg);
void print(stack *top);
char keys[512];
int i;
stack *top = (stack *)malloc(sizeof(stack));
printf("\n\n Linked Stack Example | Match Brackets ");
while (1)
{
printf("\n\n input '#' to quit ");
printf("\n brackets: ");
scanf("%s", keys);
for (i = 0; keys[i]; i++)
{
switch(keys[i])
{
case '{':
case '[':
case '(':
top = push(top, keys[i]);
break;
case '}':
if (!is_empty(top, 0) && (get_top(top) == '{'))
{
top = pop(top);
break;
}
else goto QUIT_FLAG;
case ']':
if (!is_empty(top, 0) && (get_top(top) == '['))
{
top = pop(top);
break;
}
else goto QUIT_FLAG;
case ')':
if (!is_empty(top, 0) && (get_top(top) == '('))
{
top = pop(top);
break;
}
else goto QUIT_FLAG;
case '#':
return 0;
break;
}
}
if (is_empty(top, 0))
{
printf("\n\n MATCH ");
}
else
{
QUIT_FLAG:
print(top);
printf("\n\n don't match ");
}
top = init(top);
}
return 0;
}