还没检查测试就把代码贴上来,好几处有错误!!!
顺便写了一个用栈完成10进制整数转换成8进制打印。
再写一个括号匹配检查的函数。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#define STACK_INIT_SIZE 1024
#define STACK_ADD_SIZE 1024
struct stack {
int size;
void **slot;
int top;
};
void InitStack(struct stack *sk);
void DestroyStack(struct stack *sk);
void ClearStack(struct stack *sk);
int StackEmpty(struct stack *sk);
int StackLength(struct stack *sk);
void GetTop(struct stack *sk, void **e);
void Push(struct stack *sk, void *e);
void *Pop(struct stack *sk);
void InitStack(struct stack *sk)
{
sk->slot = (void **) malloc(STACK_INIT_SIZE * sizeof(void *));
assert(sk->slot != NULL);
sk->size = STACK_INIT_SIZE;
sk->top = 0;
}
void DestroyStack(struct stack *sk)
{
free(sk->slot);
sk->size = 0;
sk->top = 0;
}
void ClearStack(struct stack *sk)
{
sk->top = 0;
}
int StackEmpty(struct stack *sk)
{
return !(sk->top);
}
int StackLength(struct stack *sk)
{
return sk->top;
}
void GetTop(struct stack *sk, void **e)
{
if (sk->top > 0) {
*e = sk->slot[sk->top - 1];
}
}
void Push(struct stack *sk, void *e)
{
sk->slot[sk->top++] = e;
if (sk->size == sk->top ) {
sk->size += STACK_ADD_SIZE;
sk->slot = realloc(sk->slot, sk->size *sizeof(void *));
assert(sk->slot != NULL);
}
}
void *Pop(struct stack *sk)
{
if (sk->top > 0) {
sk->top--;
return sk->slot[sk->top];
}
else {
printf("Warn Stack is empty\n");
return NULL;
}
}
void conversion()
{
int n;
struct stack s;
InitStack(&s);
scanf("%d", &n);
while (n) {
Push(&s, (void *) (n % 8));
n = n / 8;
}
while (!StackEmpty(&s)) {
n = (int) Pop(&s);
printf("%d", n);
}
DestroyStack(&s);
}
int BracketMatch(struct stack *s, char *str)
{
int status = 0;
char c;
while (*str != 0) {
switch (*str) {
case '(':
Push(s, (void *) *str);
break;
case ')':
if (!StackEmpty(s)) {
c = (char ) Pop(s);
if (c != '(') {
status = 1;
}
}
else {
status = 1;
}
break;
case '{':
Push(s, (void *) *str);
break;
case '}':
if (!StackEmpty(s)) {
c = (char) Pop(s);
if (c != '{') {
status = 1;
}
}
else {
status = 1;
}
break;
}
if (status == 1) {
return 1;
}
str++;
}
return 0;
}
int main(int argc, char *argv[])
{
struct stack s;
char buf[1024];
InitStack(&s);
// conversion();
printf("\n");
while (fgets(buf, sizeof(buf), stdin)) {
printf("%s", buf);
if (BracketMatch(&s, buf) != 0) {
printf("Bracket is't match\n");
return 0;
}
}
if (StackEmpty(&s)) {
printf("Bracket is match\n");
}
else {
printf("Bracket Is't match\n");
}
DestroyStack(&s);
return 0;
}