0% found this document useful (0 votes)
5 views4 pages

Java Stack and Infix to Postfix Conversion

Stack

Uploaded by

Sarthak
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views4 pages

Java Stack and Infix to Postfix Conversion

Stack

Uploaded by

Sarthak
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

Ans1:

/*class name: Stack


Data Members:
int stk[],capacity,top;
Member Functions:
Stack(int cap ): constructor to initialize the cap to
capacity and -1 to top
void pushItem(int val): to push val into the stack on the
top , if possible, otherwise outputs a message
"Stack Overflow".
int pop(): remove and return the top most element present in
to the stack. if satack is empty then print "Stack
underflow" and return -9999.
void display(): to print the elements of the stack if stack
is not empty otherwise print "Stack is empty"

*/

import [Link].*;
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)
{
[Link]("Stack overflow:");
}
else
{
top++;
stk[top]=val;
}
}
int pop()
{
if(top==-1)
{
[Link]("Stack Underflow:");
return -9999;
}
else
{
int temp= stk[top];
top--;
return temp;
}
}
void display()
{
if(top==-1)
{
[Link]("Stack is empty:");
}
else
{
for(int i=top;i>=0;i--)
{
[Link](stk[i]);
}
}
}
public static void main()
{
Scanner in = new Scanner([Link]);
[Link]("Enter the size of the stack ");
int s=[Link]();
Stack ob = new Stack(s);
int ch;
do{
[Link]("Enter 1 to push an element into the stack:");
[Link]("Enter 2 to pop an element from the stack: ");
[Link]("Enter 3 to print elements of the stack: ");
[Link]("Enter 4 to EXIT: ");

[Link]("Enter your choice: ");


ch=[Link]();
switch(ch)
{
case 1:
[Link]("Enter a value to be entered into the stack");
int val = [Link]();
[Link](val);
break;
case 2:
int t=[Link]();
[Link]("deleted element="+t);
break;
case 3:
[Link]("Elements of the stack:");
[Link]();
break;
case 4:
[Link]("Program Terminates.");
[Link](0);
default:
[Link]("Thank you:");
}
}while(ch>=1 && ch<=3);
}}

/*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 [Link].*;
class InfixToPostfix
{
public static void main()
{
Scanner in = new Scanner([Link]);
String s="",exp="";
int i,j,len,top=0;
char ch,p;
[Link]("Enter an infix expression:");
exp=[Link]();
exp="("+exp+")";
[Link]("Given Expression="+exp);
len=[Link]();
char ar[]= new char[len];
for(i=0;i<len;i++)
{
ch=[Link](i);
if(ch=='('||ch=='^')
ar[top++]=ch;
else if([Link](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];
}
[Link]("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%+

Enter an infix expression:


a/(b^4+c*d)+6
Given Expression=(a/(b^4+c*d)+6)
Output:In PostFix form:
ab4^cd*+/6+

*/

Common questions

Powered by AI

Using negative numbers like -9999 as error values risks misinterpretation of function results, especially if negative numbers are valid stack content. This can lead to application logic errors where a legitimate value is misconstrued as an error, causing incorrect behavior downstream . Mitigation could include implementing a clear exception handling mechanism, such as throwing a specific exception for stack underflow. This provides a robust, systematic way to differentiate between valid results and error states without ambiguity .

The InfixToPostfix class manages operator precedence by using a stack where operators are pushed in, and according to precedence, even popping occurs. Higher precedence operators like '^' are managed specifically alongside '+' and '-' by using loops to pop all elements of higher or equal precedence . For '*' and '/' which have higher precedence than '+' and '-', they are only pushed above the lower precedence operators . Associativity is handled through the scan order and conditional checks that decide when to pop the stack based on precedence rules. Parentheses are used to reset precedence parsing (by pushing '(' and stopping popping at '(').

Potential limitations include limited operator handling and no support for multi-character operands or variables, which restricts its usability. Hardcoding operator precedence within the loops can make the code less extendable. An extension could optimize handling multi-character operands through tokenization and employ a more comprehensive precedence map or function. Additionally, more robust error checking could be added to confirm valid expressions as input, and comments or structured documentation would improve readability and maintainability .

The capacity management in the pushItem method contributes to safety by ensuring that an item is only added if there is sufficient space. Before any item is pushed, a check against capacity-1 makes certain that the top does not exceed the initialized array size. If capacity is reached, the method outputs "Stack overflow," preventing data corruption beyond the fixed memory allocation. This protects users from inadvertently losing data or overloading internal structures, thus maintaining integrity and predictable stack manipulation .

The pop method returns an error condition by printing "Stack Underflow" and returning a sentinel value of -9999 if the stack is empty . In a real-world scenario, this can be improved by throwing an exception that more clearly indicates the stack is empty, such as an EmptyStackException. This approach provides better error propagation and management, enabling calling functions to handle the condition more explicitly and avoiding the potential misuse of unique sentinel values .

Converting infix expressions to postfix is significant because it eliminates the need for parenthesis and follows the direct order of operations, facilitating easier and faster computation in stack-based evaluations . The provided algorithm first scans the infix expression for operators and operands. Operators are pushed to a stack with appropriate precedence considerations, and operands are directly added to the result. When an operator of lower or equal precedence is encountered, the stack is popped to the result. Parentheses are managed by pushing '(' onto the stack and popping until '(' when ')' is encountered. The final expression also accounts for remaining operators in the stack .

The use of a stack in the InfixToPostfix algorithm exemplifies the LIFO principle by having operators pushed onto the stack as they are encountered and using them in reverse order of their entry. When an operator with lower precedence or a terminating parenthesis is hit, the stack is popped, removing the most recent operator first. This order ensures that postfix expression reflects precedence without needing parentheses, directly exemplifying LIFO .

The sample input/output demonstrates basic functionality by showing stack operations: pushing elements 56 and 45, printing those elements, and terminating the program. Each step reflects user choices to manage the stack . Improvements might include better user input validation, such as catching exceptions for non-numeric inputs, and expanding feedback messages. Additionally, implementing dynamic stack resizing could improve usability by circumventing overflow issues. Providing more descriptive command-line prompts could enhance user experience and intuitiveness .

The main steps for converting infix to postfix are: adding a parenthesis around the expression, iterating through each character to handle operators and operands, and utilizing a stack to store operators. The stack plays a critical role by temporarily holding operators and ensuring they are added to the postfix expression based on their precedence. When encountering closing parenthesis or operators of lower precedence, operators from the stack are appended to the postfix expression. This ensures operators are outputted in the correct order for postfix notation .

The Stack class manages overflow and underflow using conditional statements. Overflow is checked in the pushItem method. If the stack is full (top equals capacity-1), it displays a message "Stack overflow" . Underflow is handled in the pop method. If the stack is empty (top equals -1), it prints "Stack Underflow" and returns -9999 .

You might also like