Stack栈——application of stack

判断括号表达式是否平衡

  1. 平衡:example:{[]}()
  2. 不平衡:example:{[}](

判断要push的是否为括号的开始符号,也就是'(' '{' '['。如果是则push栈中,反之若是')' '}' ']',则判断栈是否为空,如果是空直接返回 no balance,若不为空c = pop栈,并与c进行匹配,匹配成功,就进行下一次的插入,反之 返回 no balance。

  1 #include<stdio.h>
  2 #include<stdlib.h>
  3 
  4 struct stack
  5 {
  6     int data;
  7     struct stack * next;
  8 };
  9 int matchParenthese(int c1, int c2)
 10 {
 11     if('(' == c1 && ')' == c2)
 12     {
 13         return 1;
 14     }
 15     else if('[' == c1 && ']' == c2)
 16     {
 17         return 1;
 18     }
 19     else if('{' == c1 && '}' == c2)
 20     {
 21         return 1;
 22     }
 23     else
 24     {
 25         return 0;
 26     }
 27 }
 28 int judgeParenthese(char ex[])
 29 {
 30     struct stack * s = NULL;
 31     int index = 0;
 32 
 33     while(ex[index])
 34     {
 35         if('(' == ex[index] || '[' == ex[index] || '{' == ex[index])
 36         {
 37             push(&s, ex[index]);
 38         }
 39         else if(')' == ex[index] || ']' == ex[index] || '}' == ex[index])
 40         {
 41             if(NULL == s)
 42             {
 43                 printf("\nThe stack is empty");
 44                 return 0;
 45             }
 46             else if(!(matchParenthese(pop(&s), ex[index])))
 47             {
 48                 return 0;
 49             }
 50 
 51         }
 52         index++;
 53     }
 54     if(NULL == s)
 55     {
 56         return 1;
 57     }
 58     else
 59     {
 60         return 0;
 61     }
 62 }
 63 struct stack * newNode(int data)
 64 {
 65     struct stack * new_node = (struct stack *)malloc(sizeof(struct stack));
 66     new_node->data = data;
 67     new_node->next = NULL;
 68 
 69     return new_node;
 70 }
 71 void push(struct stack ** root, int data)
 72 {
 73     struct stack * new_node = newNode(data);
 74 
 75     new_node->next = (*root);
 76     (*root) = (new_node);
 77     printf("\n %c pushed to stack", data);
 78 }
 79 int isEmpty(struct stack * root)
 80 {
 81     return NULL == root ? 1 : 0;
 82 }
 83 int pop(struct stack ** root)
 84 {
 85     if(isEmpty((*root)))
 86     {
 87         printf("\nUnderFlow");
 88         return 0;
 89     }
 90     struct stack * temp = (*root);
 91     int data = temp->data;
 92     (*root) = temp->next;
 93     free(temp);
 94     printf("\n The %c poped of stack", data);
 95     return data;
 96 }
 97 int peek(struct stack * root)
 98 {
 99     if(isEmpty(root))
100     {
101         printf("\nUnderFlow");
102         return 0;
103     }
104     return root->data;
105 }
106 int main(void)
107 {
108     char ex[] = "{()}[";
109     if(judgeParenthese(ex))
110     {
111         printf("\nBalance!");
112     }
113     else
114     {
115         printf("\nNO!");
116     }
117     return 0;
118 }

 

posted @ 2018-07-24 11:09  一凡夫一俗子  阅读(161)  评论(0编辑  收藏  举报