• Source
    1. #include <stdio.h>
    2. #include <stdlib.h>
    3.  
    4. struct node {
    5. char data;
    6. struct node * prev_top;
    7. };
    8.  
    9. void push( struct node ** curr_top_ref , char data )
    10. {
    11. struct node * temp_node = ( struct node * )malloc( sizeof( struct node ));
    12.  
    13. if( temp_node != NULL )
    14. {
    15. temp_node->data = data;
    16. temp_node->prev_top = *curr_top_ref;
    17. *curr_top_ref = temp_node;
    18. }
    19. }
    20.  
    21. void pop( struct node ** curr_top_ref )
    22. {
    23. struct node * top;
    24. if( curr_top_ref != NULL )
    25. {
    26. top = *curr_top_ref;
    27. *curr_top_ref = top->prev_top;
    28. free(top);
    29. }
    30. }
    31.  
    32.  
    33. int isbracketbalanced( char expr[] )
    34. {
    35. struct node * curr_stack_top = NULL;
    36. int i = 0;
    37.  
    38. while(expr[i])
    39. {
    40. if( expr[i]=='(' || expr[i] == '{' || expr[i] == '[' )
    41. {
    42. push( &curr_stack_top , expr[i] );
    43. }
    44.  
    45. if( curr_stack_top == NULL )
    46. {
    47. return 0;
    48. }
    49.  
    50. switch(expr[i])
    51. {
    52. case ')':
    53. if( curr_stack_top-> data == '(' )
    54. pop( &curr_stack_top);
    55. else
    56. return 0;
    57. break;
    58. case '}':
    59. if( curr_stack_top-> data == '{' )
    60. pop( &curr_stack_top);
    61. else
    62. return 0;
    63. break;
    64. case ']':
    65. if( curr_stack_top-> data == '[' )
    66. pop( &curr_stack_top);
    67. else
    68. return 0;
    69. break;
    70. }
    71. i++;
    72. }
    73.  
    74. if( curr_stack_top == NULL )
    75. {
    76. return 1;
    77. }
    78. else
    79. {
    80. return 0;
    81. }
    82. }
    83.  
    84. int main(void) {
    85. // your code goes here
    86. char test1[] = "{[]}";
    87. if( isbracketbalanced(test1))
    88. printf("brackets are balanced \n");
    89. else
    90. printf("brackets are not balanced \n");
    91.  
    92. return 0;
    93. }
    94.