Skip to content

Instantly share code, notes, and snippets.

@Esarve
Created November 26, 2016 17:41
Show Gist options
  • Save Esarve/c7dc3047844501d78c7f285e35d4b083 to your computer and use it in GitHub Desktop.
Save Esarve/c7dc3047844501d78c7f285e35d4b083 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Stack
{
char* elements;
int size;
int capasity;
}stack;
stack* s; //Globally declearing stack pointer
//Declearing functions...
void postfix(char arr[]);
int count(char* arr);
/*Star of stack functions */
void creatstack(int size)
{
s=(stack*)malloc(sizeof(stack));
s->elements=(char*)malloc(sizeof(char)*size);
s->capasity=size;
s->size=0;
}
void push(char data)
{
if(s->size==s->capasity)
{
printf("\nStack is full");
}
else
{
s->elements[s->size++]==data;
}
}
char top()
{
if (s->size==0)
{
printf("\nStack is Empty");
}
return s->elements[s->size-1];
}
void pop ()
{
if (s->size==0)
{
printf("\nStack is Empty");
}
else
{
s->size--;
}
}
/* End of stack functions */
void main()
{
int stacksize;
char expression[20];
printf("Input your expression: ");
gets(expression); //Input string
stacksize=count(expression); //Getting the size of stack
creatstack(stacksize); // creating a stack of the size
char temp[20];
strcpy(temp,expression); //
postfix(temp);
}
void postfix(char arr[])
{
int i,j,k;
i=j=k=0;
char temp[20];
push('(');
while (arr[i]!='\0')
{
if (arr[i]=='(')
{
push(arr[i]);
i++;
continue;
}
else if (arr[i]>='a' && arr[i]<='z')
{
temp[j]=arr[i];
i++;
j++;
continue;
}
else if (arr[i]=='*' ||arr[i]=='/')
{
while (top()=='*' || top()=='/' || top()=='+'||top()=='-')
{
temp[j]=top();
pop();
j++;
}
if (top()=='(')
{
push(arr[i]);
i++;
continue;
}
}
else if (arr[i]=='+' ||arr[i]=='-')
{
while (top()=='*' || top()=='/')
{
temp[j]=top();
pop();
j++;
}
if (top()=='+' || top()=='-'|| top()=='('|| top()==')')
{
push(arr[i]);
i++;
continue;
}
}
if (arr[i]==')')
{
while (top()!='(')
{
temp[j]=top();
pop();
j++;
}
push(arr[i]);
i++;
continue;
}
}
strcpy(arr,temp);
printf("\n");
puts(arr);
}
int count(char* arr)
{
int i,c;
i=c=0;
while (*(arr+i)!='\0')
{
if (*(arr+i)=='+'|| *(arr+i)=='-'||*(arr+i)=='*'||*(arr+i)=='/'||*(arr+i)=='('||*(arr+i)==')'||*(arr+i)=='^')
{
c++;
i++;
}
else
i++;
}
return i;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment