Infix to Postfix using C

Infix to Postfix using C – 32 PPT – Albert Hendry Harsono (1701296914)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char op[50];
struct node
{
    char data;
    struct node *next;
}*head=0;
void push(char x)
{
    if(head==NULL)
    {
        head=(struct node *)malloc(sizeof(struct node));
        head->data=x;
        head->next=NULL;
    }
    else
    {
        struct node *p;
        p=(struct node *)malloc(sizeof(struct node));
        p->data=x;
        p->next=head;
        head=p;
    }
}
char pop()
{
    char c;
    struct node *p;

	if (head==NULL)
    {
        printf("the stack is empty\n");
    }

	else
    {
        c=head->data;
        p=head->next;
        free (head);
        head=p;
    }
    return c;
}
void display(struct node *start)
{
    {
        struct node *p;
        p=start;
        if(p==NULL)
            printf("Empty list");
        else
        {
            while(p!=NULL)
            {
                printf("%c->",p->data);
                p=p->next;
            }
            printf("NULL\n");
        }
    }
}
int priority(char s, char c)
{
    if ( (c=='^' && s=='+') || s=='-' ||s=='/' || s=='*')
        return 1;
    else if( c=='*' || c=='/')
    {
        if(s=='+' || s=='-' )
            return 1;
        else
            return 0;
    }
    else if( c=='+' || c=='-' )
        return 0;
  return -1;
}
void convert(char s[], int n)
{
    int i,j;//,x;
    for(i=0,j=0;i<n;i++)     {         if ((s[i]>='0'&&s[i]<='9') || (s[i]>='a' && s[i]<='z')|| (s[i]>='A' && s[i]<='Z'))         {             op[j]=s[i];             j++;         }         else if(s[i]=='(')         {             push(s[i]);         }         else if (s[i]=='+' || s[i]=='/' || s[i]=='-' || s[i]=='*' || s[i]=='^')         {             if( head==NULL)                 push(s[i]);             else if(head->data=='(')
                push(s[i]);
            else if(priority(head->data, s[i] )!=1)
                push(s[i]);
            else
            { op[j]=pop();
                j++;
                push(s[i]);
            }
        }
        else if(s[i]==')')
        {
            while(head!=NULL && head->data!='(')
            {
                op[j]=pop();
                j++;
            }
            pop();
        }
    }
    while(head!=NULL)
    {
        op[j]=pop();
        j++;
    }
}
int main()
{
    int i,n;
    char c[50];
    n=strlen(c);

	do
	{
		printf("Masukkan Infix [max 50 karakter]: ");
		scanf("%s",c);
	}while(n>50 || n<1);
	n=strlen(c);
    convert(c,n);
    printf("Notasi postfix-nya adalah: ");
    for(i=0;i<n;i++)
    {
		printf("%c",op[i]);
    }
	getchar();
	getchar();
    return 0;
}
This entry was posted in Struktur Data, Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *