Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- //typedef int StackElement;
- typedef float StackElement;
- struct Stack
- {
- StackElement* data;
- int top;
- int cap;
- };
- typedef struct Stack Stack;
- void initStack(Stack* s, int cap)
- {
- s->data=malloc(cap*sizeof(StackElement));
- s->top=-1;
- s->cap=cap;
- }
- void destroyStack(Stack* s)
- {
- free(s->data);
- }
- void push(Stack* s, StackElement el)
- {
- if(s->top==s->cap-1)
- {
- printf("Stek je pun\n");
- exit(1);
- }
- s->top++;
- s->data[s->top]=el;
- }
- int isEmpty( Stack* s)
- {
- if(s->top==-1)
- return 1;
- return 0;
- }
- StackElement pop(Stack* s)
- {
- if (isEmpty(s))
- {
- printf("Stek je prazan\n");
- exit(2);
- }
- s->top--;
- return s->data[s->top+1];
- }
- StackElement top(Stack* s)
- {
- if (isEmpty(s))
- {
- printf("Stek je prazan\n");
- exit(2);
- }
- return s->data[s->top];
- }
- //napisati funkciju koja vrace true ako je dat pravilan niz zagrada
- int zagrade(char * str)
- {
- int n=strlen(str);
- Stack s;
- initStack(&s,n);
- int i;
- for(i=0;i<n;i++)
- {
- if(str[i]==' ')
- continue;
- if(str[i]=='(' || str[i]=='[' || str[i]=='{')
- push(&s,str[i]);
- else
- {
- if(isEmpty(&s))
- {
- destroyStack(&s);
- return 0;
- }
- char t=pop(&s);
- if(str[i]==')')
- if(t!='(')
- {
- destroyStack(&s);
- return 0;
- }
- if(str[i]==']')
- if(t!='[')
- {
- destroyStack(&s);
- return 0;
- }
- if(str[i]=='}')
- if(t!='{')
- {
- destroyStack(&s);
- return 0;
- }
- }
- }
- if(isEmpty(&s))
- {
- destroyStack(&s);
- return 1;
- }
- destroyStack(&s);
- return 0;
- }
- void validneZagrade(char * str)
- {
- if(zagrade(str))
- printf("Izraz je validan\n");
- else printf("Izraz nije validan\n");
- }
- float postfixValue(char* str)
- {
- int n=strlen(str);
- Stack s;
- initStack(&s,n);
- int i;
- for(i=0;i<n;i++)
- {
- if(str[i]>='0'&& str[i]<='9')
- push(&s,(float)str[i]-'0');
- else
- {
- float op1=pop(&s);
- float op2=pop(&s);
- switch(str[i])
- {
- case '+':
- push(&s,op1+op2);
- break;
- case '-':
- push(&s,op2-op1);
- break;
- case '*':
- push(&s,op1*op2);
- break;
- case '/':
- push(&s,op2/op1);
- break;
- }
- }
- }
- float rez=pop(&s);
- destroyStack(&s);
- return rez;
- }
- int main()
- {
- Stack s;
- initStack(&s,5);
- push(&s,5);
- push(&s,31);
- push(&s,2);
- push(&s,53);
- //printf("%d\n",pop(&s));
- char str[100];
- gets(str);
- //validneZagrade(str);
- printf("%f",postfixValue(str));
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement