Stack Infix
Stack Infix
*/
import java.util.*;
class Stack
{
int stk[], capacity, top;
Stack(int cap)
{
capacity = cap;
top=-1;
stk= new int [capacity];
}
void pushItem(int val)
{
if(top==capacity-1)
{
System.out.println("Stack overflow:");
}
else
{
top++;
stk[top]=val;
}
}
int pop()
{
if(top==-1)
{
System.out.println("Stack Underflow:");
return -9999;
}
else
{
int temp= stk[top];
top--;
return temp;
}
}
void display()
{
if(top==-1)
{
System.out.println("Stack is empty:");
}
else
{
for(int i=top;i>=0;i--)
{
System.out.println(stk[i]);
}
}
}
public static void main()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the size of the stack ");
int s=in.nextInt();
Stack ob = new Stack(s);
int ch;
do{
System.out.println("Enter 1 to push an element into the stack:");
System.out.println("Enter 2 to pop an element from the stack: ");
System.out.println("Enter 3 to print elements of the stack: ");
System.out.println("Enter 4 to EXIT: ");
/*Sample Input/Output:
Enter the size of the stack
4
Enter 1 to push an element into the stack:
Enter 2 to pop an element from the stack:
Enter 3 to print elements of the stack:
Enter 4 to EXIT:
Enter your choice:
1
Enter a value to be entered into the stack
56
Enter 1 to push an element into the stack:
Enter 2 to pop an element from the stack:
Enter 3 to print elements of the stack:
Enter 4 to EXIT:
Enter your choice:
1
Enter a value to be entered into the stack
45
Enter 1 to push an element into the stack:
Enter 2 to pop an element from the stack:
Enter 3 to print elements of the stack:
Enter 4 to EXIT:
Enter your choice:
3
Elements of the stack:
45
56
Enter 1 to push an element into the stack:
Enter 2 to pop an element from the stack:
Enter 3 to print elements of the stack:
Enter 4 to EXIT:
Enter your choice:
4
Program Terminates.
*/
Ans3:
import java.util.*;
class InfixToPostfix
{
public static void main()
{
Scanner in = new Scanner(System.in);
String s="",exp="";
int i,j,len,top=0;
char ch,p;
System.out.println("Enter an infix expression:");
exp=in.next();
exp="("+exp+")";
System.out.println("Given Expression="+exp);
len=exp.length();
char ar[]= new char[len];
for(i=0;i<len;i++)
{
ch=exp.charAt(i);
if(ch=='('||ch=='^')
ar[top++]=ch;
else if(Character.isLetterOrDigit(ch))
s=s+ch;
else
{
if(ch=='+'||ch=='-'||ch==')')
{
for(j=top-1;j>0;j--)
{
p=ar[j];
if(p!='(')
{
s=s+p;
top--;
}
else
break;
}//closing of j loop
if(ch!=')')
ar[top++]=ch;
else
top-=1;
}//closing of if(ch=='+'||ch=='-')
else if(ch=='*'||ch=='%'||ch=='/')
{
for(j=top-1;j>0;j--)
{
p=ar[j];
if(p!='(' && p!='+' && p!='-')
{
s=s+p;
top--;
}
else
break;
}//closing of j loop
ar[top++]=ch;
}//closing of else if(ch=='*'||ch=='%'||ch=='/')
}//closing of else
}//closing of i loop
for(i=top-1;i>0;i--)
{
s=s+ar[i];
}
System.out.println("Output:In PostFix form:\n"+s);
}}
/*SampleInput/Output:
Enter an infix expression:
a+(b*c+d^3)%r
Given Expression=(a+(b*c+d^3)%r)
Output:In PostFix form:
abc*d3^+r%+
*/