Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "pch.h"
- #include <iostream>
- typedef struct Stack
- {
- int* values;
- unsigned size;
- int top_index;
- } stack;
- void init_stack(stack* stack, unsigned size);
- void free_stack(stack* stack);
- void push(stack* stack, int value);//Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.
- int peek(stack* stack);//Returns top element of stack.
- int pop(stack* stack);//Removes an item from the stack.
- int is_full(stack* stack);
- int isEmpty(stack* stack);
- void print_stack(stack* stack);
- void print_info(stack* stack);
- char get_pair(char br);
- int brackets(char* str);
- int main()
- {
- stack stack;
- init_stack(&stack, 5);
- //print_stack(&stack);
- push(&stack, 3);
- push(&stack, 4);
- push(&stack, 3);
- push(&stack, 2);
- push(&stack, 7);
- print_stack(&stack);
- //printf("\n%d",peek(&stack));
- printf("%d", stack.top_index);
- pop(&stack);
- printf("\n");
- print_stack(&stack);
- printf("%d", stack.top_index);
- free_stack(&stack);
- char str[50] = "(a+b)( *c*c[d-e]";
- int res = brackets(str);
- if (res == -1)
- {
- printf("Correct\n");
- }
- else
- {
- printf("error in position %d", res);
- }
- return 0;
- }
- void init_stack(stack* stack, unsigned size)
- {
- stack->values = (int*)malloc(sizeof(int)*size);
- stack->top_index = -1;
- stack->size = size;
- return;
- }
- int is_full(stack* stack)// Stack is full when top is equal to the last index
- {
- return stack->top_index == stack->size-1;
- }
- int isEmpty(stack* stack)
- {
- return stack->top_index == -1;
- }
- void free_stack(stack* stack)
- {
- free(stack->values);
- return;
- }
- void push(stack* stack, int value)
- {
- if (is_full(stack))
- return;
- stack->values[++stack->top_index] = value;
- }
- int peek(stack* stack)
- {
- return stack->values[stack->top_index];
- }
- int pop(stack* stack)
- {
- if (isEmpty(stack))
- return -1;
- int item =stack->values[stack->top_index];
- (stack->top_index) -= 1; // top = top - 1
- return item;
- }
- void print_stack(stack* stack)
- {
- for (int i = 0; i < stack->top_index; i++)
- {
- printf("%3d", stack->values[i]);
- }
- }
- void print_info(stack* stack)
- {
- }
- char get_pair(char br)
- {
- switch (br)
- {
- case'(':return')';
- case'[':return']';
- case'{':return'}';
- case'<':return'>';
- }
- }
- int brackets(char* str)
- {
- stack st;
- init_stack(&st, strlen(str));
- int i = 0;
- while (str[i])
- {
- switch (str[i])
- {
- case'(':
- case'[':
- case'{':
- case'<':
- push(&st, str[i]);
- break;
- case')':
- case']':
- case'}':
- case'>':
- if (isEmpty(&st))
- {
- return i;
- }
- if (str[i] != get_pair(pop(&st)))
- {
- return i;
- }
- default:break;
- }
- i++;
- }
- if (!isEmpty(&st))
- {
- return i;
- }
- return -1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement