amrendra2018

Untitled

Aug 11th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. Program for checking balance of parenthesis in C using stack but it is not working as expected plz help me with it. Thanks
  2.  
  3. #include<stdio.h>
  4. #include<stdlib.h>
  5. #include<string.h>
  6. struct node{
  7. char data;
  8. struct node *next;
  9. };
  10. struct node *top=NULL; //top stores address of top element of stack
  11. void push(char data) //inserting element
  12. {
  13. struct node *temp = (node *)malloc(sizeof(struct node));
  14. temp->data=data;
  15. temp->next=NULL;
  16. if(top==NULL)
  17. {
  18. top=temp;
  19. return;
  20. }
  21. temp->next=top;
  22. top=temp;
  23. }
  24. void pop() //removing element
  25. {
  26. struct node *temp=top;
  27. if(top==NULL)
  28. {
  29. printf("No element to delete");
  30. return;
  31. }
  32. top=top->next;
  33. free(temp);
  34. }
  35. char Top() //fn tht return top element of stack
  36. {
  37. return top->data;
  38. }
  39. int isEmpty()
  40. {
  41. if( top!=NULL)
  42. {
  43. return 1;
  44. }
  45. else
  46. return 0;
  47. }
  48. int ArePair(char opening,char closing)
  49. {
  50. if(opening == '(' && closing == ')')
  51. return 1;
  52. else if(opening == '{' && closing == '}')
  53. return 1;
  54. else if(opening == '[' && closing == ']')
  55. return 1;
  56. return 0;
  57. }
  58. int Arebalanced(char exp[])
  59. {
  60. int i;
  61. for(i=0;i<strlen(exp);i++)
  62. {
  63. if(exp[i] == '(' || exp[i] == '{' || exp[i] == '[')
  64. push(exp[i]);
  65. else if(exp[i] == ')' || exp[i] == '}' || exp[i] == ']')
  66. {
  67. if(isEmpty() || !ArePair(Top(),exp[i]))
  68. return 0;
  69. else
  70. pop();
  71. }
  72. }
  73. return isEmpty() ? 1:0;
  74. }
  75. int main()
  76. {
  77. int i;
  78. char a[50];
  79. printf("Enter expession: ");
  80. gets(a);
  81. if(Arebalanced(a))
  82. {
  83. printf("balanced \n");
  84. }
  85. else
  86. printf("not balanced\n");
  87. }
Add Comment
Please, Sign In to add comment