1. 程式人生 > >順序棧 & 順序棧的括號匹配演算法

順序棧 & 順序棧的括號匹配演算法

棧空時 S->top = -1
新增第一個元素過程:
S->data[s->top++] = value;

#include <stdio.h>
#include <stdlib.h>
#define MAXLINE 100

typedef struct
{
    int data[MAXLINE];
    int top;
}sql_stack;

//順序棧的初始化
void init_sqlstack(sql_stack **s)
{
      *s = (sql_stack *)malloc(sizeof(sql_stack));
     (*s)->top = -1
; } //入棧 void push_sqlstack(sql_stack *s,int value) { if(s->top == MAXLINE-1) { printf("stack is full\n"); exit(1); } s->top++; s->data[s->top] = value; } //取棧頂 void pop_sqlstack(sql_stack *s,int *value) { *value = s->data[s->top--]; printf("%d "
,*value); } int main(int argc,char **argv) { sql_stack *s = NULL; int i = 0; int value = 0; init_sqlstack(&s); for(i = 0;i < 5;++i) { push_sqlstack(s,rand()%10); } while(s->top != -1) { pop_sqlstack(s,&value); } printf("\n"
); return 0; }

順序棧的括號匹配演算法:

#include <stdio.h>
#include <stdlib.h>
#define MAXLINE 100

typedef struct
{
    char data[MAXLINE];
    int top;
}sql_stack;

//順序棧的初始化
void init_sqlstack(sql_stack **s)
{
      *s = (sql_stack *)malloc(sizeof(sql_stack));
     (*s)->top = -1;
}

//入棧
void push_sqlstack(sql_stack *s,char value)
{
     if(s->top == MAXLINE-1)
     {
        printf("stack is full\n");
        exit(1);
     }
     s->top++;
     s->data[s->top] = value;
}

//取棧頂
void pop_sqlstack(sql_stack *s,char *value)
{
    if(s->top != -1)
    {
        *value = s->data[s->top--];
    //printf("%d ",*value);
    }
}

int main(int argc,char **argv)
{
     sql_stack *s = NULL;

     init_sqlstack(&s);
     char rev[MAXLINE];
     char value;
     char *ch = rev;
     printf("輸入表示式:\n");
     scanf("%s",rev);
     while(*ch != EOF){
         if(*ch =='(' || *ch == '{' || *ch =='['){
             push_sqlstack(s,*ch);
             //printf("%c",*ch);
         }
         if(*ch == ')')
         {
            pop_sqlstack(s,&value);
            //printf("%c",value);
            if(value != '('){
               printf("括號不匹配\n");
               return 1;
            }
         }

         if(*ch == ']')
         {
            pop_sqlstack(s,&value);
            //printf("%c",value);
            if(value != '['){
               printf("括號不匹配\n");
               return 1;
            }
         }

         if(*ch == '}')
         {
            pop_sqlstack(s,&value);
           // printf("%c",value);
            if(value != '{'){
               printf("括號不匹配\n");
               return 1;
            }
         }

         ch++;
     }
     printf("括號匹配成功\n");
     return 0;
}