Showing posts with label Stack in C. Show all posts
Showing posts with label Stack in C. Show all posts

Monday, June 18, 2012

Program on entering infix expression and evaluation of the expression after converting in postfix using stack


Here in this program the user will enter an infix expression , the infix will be displayed in postfix notation and the evaluated value of the postfix notation will be displayed.

# include< stdio.h>
# include< stdlib.h>
struct link
{
char ch;
struct link *next;
};

/*This structure is defined to store the operators of the infix notation.The operands of the infix notation will be displayed and the operators of the expression will be displayed according to precedence. functions push() , pop() , pop1() and pop2() are related with this staructure type stack */

struct link *dd1=NULL,*dd2;

/*these two external pointers will be used to store the postfix version of the expression in a stack.*/

struct list
{
int num;
char ch;
struct list *next;
};

/*This structure will be used to store the operands of the converted postfix notation*/

struct list *last=NULL;
struct link * pop2(struct link *rec)
{
char ch='a';
struct link *temp;
char x;
while((ch!='(')&&(rec!=NULL))
{
x=rec->ch;
if(x!='(')
{
dd2=(struct link *)malloc(sizeof(struct link));
dd2->ch=x;
dd2->next=dd1;
dd1=dd2;
/*operator stored in the stack for postfix evaluation*/
printf("%c",x);
/* operator is displayed for the postfix version*/
}
temp=rec->next;
free(rec);
/*stack which contains the operators for postfix version shrinks as the operator is displayed.*/
rec=temp;
}
return rec;
}
struct link * pop(struct link *rec)
{
if(rec != NULL)
{
struct link *temp;
char x;
x=rec->ch;
if(x!='(')
{
dd2=(struct link *)malloc(sizeof(struct link));
dd2->ch=x;
dd2->next=dd1;
dd1=dd2;
printf("%c",x);
}
temp=rec->next;
free(rec);
rec=temp;
}
return rec;
}
struct link * pop1(char z,struct link *rec)
{
struct link *temp;
char x;
x=rec->ch;
if(((x=='+')||(x=='-'))&&((z=='*')||(z=='/')||(z=='%')))
{

/*if the current operator has more precedence over the top item of the stack then no action should be taken , they should be kept in the stack as it is.Otherwise the last inserted item ( here operator) should be displayed ( from the else part).*/

}
else
{
if(x!='(')
{
dd2=(struct link *)malloc(sizeof(struct link));
dd2->ch=x;
dd2->next=dd1;
dd1=dd2;
/*the operator is stored in the stack no 2 (for postfix evaluation)*/
printf("%c",x);
}
temp=rec->next;
free(rec);
rec=temp;
/* if the top item of the stack is displayed , the stack should shrink.*/
}
return rec;
}
struct link *push(char c,struct link *rec)
{
if(c==')')
{
//if clossing bracket is found , there must be a openning bracket with operator
rec=pop2(rec);
}
if((rec!=NULL)&&(c!='('))
{

/*if the stack contains an operator and another operator is encountered, the operator which is of more precedence should be displayed.*/

rec=pop1(c,rec);
}
if(c!=')')
{
// from this block the current encountered operator is stored in the stack
struct link *new1;
new1 = (struct link *)malloc(sizeof(struct link));
new1->ch=c;
new1->next = rec;
rec = new1;
}
return rec;
}
struct list *push1(int i,struct list *node)
{
struct list *new1;
new1=(struct list *)malloc(sizeof(struct list));
new1->num=i;
new1->next=node;
node=new1;
return node;
}
struct list *pop3(struct list *node)
{
struct list *p;
p=node->next;
free(node);
node=p;
return node;
}

void dis(struct link *node)
{
int x,y,result;
struct list *ds,*sta=NULL;
while(node)
{
ds=(struct list *)malloc(sizeof(struct list));
ds->ch=node->ch;
node=node->next;
ds->next=last;
last=ds;
}

/* elements of the second stack are stored in another stack in reversed order whose top element is pointed by external pointer last.Now each element of the stack will be checked , if operand is found then it will be pushed in another stack , in case of operator the top two operands will be poped from the stack and operation will be performed according to the operator and the result will be pushed back again in the stack.*/

while(last)
{
char c=last->ch;
if(isdigit(c)!=0)
sta=push1(c-48,sta);
else
{
y=sta->num;
sta=pop3(sta);
x=sta->num;
sta=pop3(sta);
switch(c)
{

/*from here the result is calculated as per the operator and the result is pushed back into the stack*/

case '+':
{
result=(x+y);
sta=push1(result,sta);
break;
}
case '-':
{
result=(x-y);
sta=push1(result,sta);
break;
}
case '*':
{
result=(x*y);
sta=push1(result,sta);
break;
}
case '/':
{
result=(x/y);
sta=push1(result,sta);
break;
}
}
}
last=last->next;

/* pointer last which is traversing the stack containg the postfix version in reversed order moves to the next node.*/

}

/* when all the operations are performed , the final stack contains only one item , the result.*/

printf("\n*****\nResult of the expression is::%d",sta->num);
}
void main()
{
struct link *start;
int i=0;
char ch='a';
clrscr();
start = NULL;
printf("\nEnter the expression:-");
while(ch!='\n')
{
ch=getchar();
if((ch=='+')||(ch=='-')||(ch=='*')||(ch=='/')||(ch=='(')||
(ch=='%')||(ch==')'))
{

/* when operators are encountered ,push method is called with the character and structure pointer as argument. current stack will be returned. */

start=push(ch,start);
i++;
}
else
{
/* this block will be executed is the character read from the input is not an operator*/

if(ch!='\n')
{
printf("%c",ch);
/*operand in postfix version is displayed.*/
dd2=(struct link *)malloc(sizeof(struct link));
dd2->ch=ch;
dd2->next=dd1;
dd1=dd2;
/* the operands are stored in stack no.2 (for postfix evaluation)*/
}
}
}
while(i>0)
{

/* i counts the number of operators in the infix expression, although at present all the operators may not be present in the stack but we should call the pop method to display the remaining operators in the stack( which are not displayed through pop1() or pop2() */

start=pop(start);

/* every call to this function will display the top element of the stack and then the stack will be shrinked and returned so , before i becomes 0 start may point to NULL*/

i--;
}
dis(dd1);

/*dis () function of the second structure is called to reverse the elements of the second stack where all the operators and operands are stored in postfix notation */

getch();
}

Evaluation of entered postfix expression using C data Structure


In this program, enter any postfix expression , the expression will be evaluated and the result will be displayed (e.g if the entered expression is 889*-88*- the result will display –128 )

Here are the codes of the program

# include < stdio.h>
# include < stdlib.h>
struct list
{
int num;
struct list *next;
};
struct list *push(int i,struct list *node)
{
struct list *new1;
new1=(struct list *)malloc(sizeof(struct list));
new1->num=i;
new1->next=node;
node=new1;
return node;
}
struct list *pop(struct list *node)
{
struct list *p;
p=node->next;
free(node);
node=p;
return node;
}
void main()
{
struct list *start=NULL;
char c;
int x,y,result;
clrscr();
printf("\nEnter the expression:-");
while((c=getchar())!='\n')
{
if(isdigit(c)!=0)
start=push(c-48,start);
else
{
y=start->num;
start=pop(start);
x=start->num;
start=pop(start);
switch(c)
{
case '+':
{
result=(x+y);
start=push(result,start);
break;
}
case '-':
{
result=(x-y);
start=push(result,start);
break;
}
case '*':
{

result=(x*y);
start=push(result,start);
break;
}
case '/':
{
result=(x/y);
start=push(result,start);
break;
}
}
}
}
printf("Result of the expression is::%d",start->num);
getch();
}

In this program the expression is taken as a string value and each character is checked whether it is digit or non digit. For digits, the element is pushed in a stack and for operators, two elements from the stack are popped from the stack. After evaluating the popped elements according to operator, the result is again pushed on the stack. Ultimately, the stack contains one element and that is the result.

Conversion of infix to postfix expression


# include< stdio.h>
# include< stdlib.h>
struct link
{
char ch;
struct link *next;
};
struct link * pop2(struct link *rec)
{
char ch='a';
struct link *temp;
char x;
while((ch!='(')&&(rec!=NULL))
{
x=rec->ch;
if(x!='(')
printf("%c",x);
temp=rec->next;
free(rec);
rec=temp;
}
return rec;
}
struct link * pop(struct link *rec)
{
if(rec != NULL)
{
struct link *temp;
char x;
x=rec->ch;
if(x!='(')
printf("%c",x);
temp=rec->next;
free(rec);
rec=temp;
}
return rec;
}
struct link * pop1(char z,struct link *rec)
{
struct link *temp;
char x;
x=rec->ch;
if(((x=='+')||(x=='-'))&&((z=='*')||(z=='/')||(z=='%')))
{
}
else
{
if(x!='(')
printf("%c",x);
temp=rec->next;
free(rec);
rec=temp;
}
return rec;
}
struct link *push(char c,struct link *rec)
{
if(c==')')
{
rec=pop2(rec);
}
if((rec!=NULL)&&(c!='('))
{
rec=pop1(c,rec);
}
if(c!=')')
{
struct link *new1;
new1 = (struct link *)malloc(sizeof(struct link));
new1->ch=c;
new1->next = rec;
rec = new1;
}
return rec;
}
void main()
{
struct link *start ;
int i=0;
char ch='a';
clrscr();
start = NULL;
printf("\nEnter the expression:-");
while(ch!='\n')
{
ch=getchar();
if((ch=='+')||(ch=='-')||(ch=='*')||(ch=='/')||(ch=='(')||(ch=='%')||(ch==')'))
{
start=push(ch,start);
i++;
}
else
{
if(ch!='\n')
printf("%c",ch);
}
}
while(i>0)
{
start=pop(start);
i--;
}
getch();
}

Sunday, June 17, 2012

Application of stack-parentheses checking in an expression


Let us see how we can use stack in problem solving. Consider a mathematical expression which contains a sets of nested parentheses— (x-(a+b) *(x-y)) and we have to check whether the parentheses are nested correctly. Actually we have to check two points.
There are equal numbers of left and right parentheses.
Every right parenthesis is preceded by a matching left parenthesis.

Expression such as ((A+B) violates first condition and expressionsuch as (A+B} * { C+D) violates the second condition.

To solve such problem, we have to design a stack where each opening parentheses ‘(‘ , ‘{‘ or ‘[‘ of the expression will be pushed and when any closing parentheses is encountered , last inserted item from the stack will popped and checked with the closing parentheses. If mismatch is found, the expression is incorrect. At the end of the push and pop operation the stack should be empty to ensure that there are equal number opening and closing parentheses.


# include< stdio.h >
# include< stdlib.h>
int b=0;
struct link
{
char info;
struct link *next;
};
char xxx;
struct link *push(char c,struct link *rec)
{
struct link *new1;
xxx=c;
new1 = (struct link *)malloc(sizeof(struct link));
new1->info=xxx;
new1->next = rec;
rec = new1;
/* Every new opening parentheses is pushed at the top of the stack and pointer rec is made to point the new location */
return rec;
}
struct link * pop(char ch,struct link *rec)
{
struct link *temp;
char xx;
if(rec == NULL)
{
printf("Number of closing parentheses is more than number of closing\n");
b++;
}
else
{
temp=rec->next;
xx=rec->info;
if((xx=='(')&&(ch==')'))
{
free(rec);
rec = temp;
}
else if((xx=='{')&&(ch=='}'))
{
free(rec);
rec = temp;
}
else if((xx=='[')&&(ch==']'))
{
free(rec);
rec = temp;
}
else
{
b++;
}
}
return rec;
}
void main()
{
struct link *start ;
int d;
char ch='a';
clrscr();
start = NULL;
printf("\nEnter the expression:-");
while(ch!='\n')
{
ch=getchar();
if((ch=='(')||(ch=='{')||(ch=='['))
{
start=push(ch,start);
}
if((ch==')')||(ch=='}')||(ch==']'))
{
start=pop(ch,start);
}
if(b!=0)
break;
}
if(b!=0)
// mismatch is found.
printf("Expression is not Correct.");
else if(start==NULL)
/* this indicates that all items from the stack are poped and no mismatch was found. */
printf("Correct Expression.");
else
/* This point indicates that no mismatch is found but still there are items in the stack. So mismatch in number of opening and closing parentheses. */
printf("Expression is not Correct.");
getch();
}


C program on stack using doubly linked list


So far we have seen array implementation of stack, stack using linear linked list. Today we will see stack using doubly linked list. Create stack, then push items in it and pop items from it.

# include< stdio.h >
# include< stdlib.h>
struct link
{
int info;
struct link *next;
struct link *prev;
};
void display(struct link *rec)
{
while(rec != NULL)
{
printf(" %d ",rec->info);
rec = rec->next;
}
}
struct link * push(struct link *rec)
{
struct link *new1;
printf("\n Enter value for stack:-");
new1 = (struct link *)malloc(sizeof(struct link));
scanf("%d", &new1->info);
new1->next = rec;
/* next pointer of new1 is holding the address of the first node of the list. so new1 is the first node now.*/
rec->prev=new1;
rec = new1;
/* from this point the pointer rec is pointing the first node of the list. */
return rec;
}
struct link * pop(struct link *rec)
{
struct link *temp;
if(rec == NULL)
{
printf("\n Stack is empty");
}
else
{
/*rec is pointing the first node of the list. */
temp = rec->next;
/* temp is pointing the second node of the list.*/
rec->next->prev=temp;
free(rec);
rec = temp;
printf("\n After pop operation the stack is as follows:\n");
display(rec);
if(rec == NULL)
printf("\n Stack is empty");
}
return rec;
}
int selection()
{
int choice;
do
{
printf("\n 1<-Push ");
printf("\n 2<-Pop");
printf("\n 3<-Quit");
printf("\n Input your choice :");
scanf("%d", &choice);
if(choice <1 || choice >3)
printf("\n Incorrect choice-> Try once again");
} while(choice <1 || choice >3);
return choice;
}
void main()
{
struct link *start ;
int choice;
clrscr();
start = NULL;
do
{
choice = selection();
switch(choice)
{
case 1:
start = push(start);
printf("\n After push operation stack is as follows:\n");
display(start);
break;
case 2:
start = pop(start);
break;
default :
printf("\n End of session");
}
} while(choice != 3);
getch();
}

C Program on reversing linked list using stack


Create a linked list and then convert it into a stack. Again the stack is to be convert into a linked list so that the linked list is reversed.

#include< stdio.h>
#include< stdlib.h>
struct tag
{
int a;
struct tag *next;
};
int i=0;
struct tag *node,*p,*p1;
void create(struct tag *n)
{
char ch;
node=n;
printf("\n Want to create(y/n)");
ch=getche();
while(ch!='n')
{
node->next=(struct tag*)malloc(sizeof(struct tag));
node=node->next;
printf("\n Value");
scanf("%d",&node->a);
printf("\nany more(y/n)");
ch=getche();
}
node->next=NULL;
}
void display(struct tag*n)
{
node=n;
if(node==NULL)
i=0;
else
i=1;
while(node)
{
printf("%4d",node->a);
node=node->next;
}
}
struct tag *push(struct tag *p1,struct tag *p2)
{
p2->next=p1;
return(p2);
}
struct tag *delF(struct tag *n)
{
node=n->next;
n->next=node->next;
return(node);
}
struct tag *pop(struct tag *n)
{
node=n->next;
free(n);
return node;
}
void main()
{
struct tag *n,*link,*stack,*p;
clrscr();
link=NULL;
stack=NULL;
create(link);
printf("\nList is as follows\n");
display(link->next);
do
{
p=delF(link);
stack=push(stack,p);
}while(link->next!=NULL);
printf("\nList is as follows (after converting it into a stack.)");
display(link->next);
if(i==0)
printf("\nNo element in the list.");
printf("\nStack is\n");
display(stack);
n=link;
while(stack!=NULL)
{
n->next=stack;
n=n->next;
stack=pop(stack);
}
printf("\nStack is as follows (after converting it into a linked list.)");
display(stack);
if(i==0)
printf("\nNo element in the stack.");
printf("\nFinal list\n");
display(link->next);
getch();
}

Subscribe via email

Enter your email address:

Delivered by FeedBurner