Lab 6
Lab 6
K K
push('E'); push('K'); push('G');
E E E
top is 1 top is 2 top is 3
Stack Operations Example
After three pops, top == 0 and the stack is empty
K
pop(); pop(); pop();
(remove G) E (remove K) E (remove E)
Array Implementation
char s[STACK_SIZE];
int top=0;
To check if stack is empty:
bool isEmpty()
{
if (top == 0)
return true;
else return false;
}
char s[STACK_SIZE];
int top=0;
To check if stack is full:
bool isFull()
{
if (top == STACK_SIZE)
return true;
else return false;
}
To add an item to the stack
void push(char x)
{
if (isFull())
{error(); exit(1);}
// or could throw an
exception
s[top] = x;
top++;
}
To remove an item from the stack
void pop(char &x)
{
if (isEmpty())
{error(); exit(1);}
// or could throw an
exception
top--;
x = s[top];
}
Dynamic Stacks
• Implemented as a linked list
• Can grow and shrink as necessary
• Can't ever be full as long as memory is
available
Discussion
• How we will implement a dynamic stack using
linked list?
Application of Stacks
• Adding large numbers
• Infix to Postfix Conversion
• Evaluating Postfix notations
• Bracket Matching
• Tower of Hanoi
• Identifying Palindromes
• Searching in Graphs (Depth First Search)
• Undo Redo
• Backtracking
Adding large numbers
Infix to Postfix conversion
Rules of Operator Precedence
Infix to postfix conversion
• Rules to follow:
– Print operands as they arrive.
– If the stack is empty or contains a left parenthesis on top, push the incoming operator
onto the stack.
– If the incoming symbol is a left parenthesis, push it on the stack.
– If the incoming symbol is a right parenthesis, pop the stack and print the operators until
you see a left parenthesis. Discard the pair of parentheses.
– If the incoming symbol has higher precedence than the top of the stack, push it on the
stack.
– If the incoming symbol has equal precedence with the top of the stack, use association.
If the association is left to right, pop and print the top of the stack and then push the
incoming operator. If the association is right to left, push the incoming operator.
– If the incoming symbol has lower precedence than the symbol on the top of the stack,
pop the stack and print the top operator. Then test the incoming operator against the
new top of stack.
– At the end of the expression, pop and print all operators on the stack. (No parentheses
should remain.)
Example Expression
Postfix Evaluation
• Rules to follow
• If the element is a number, push it into the stack
• If the element is a operator, pop operands for the operator
from stack. Evaluate the operator and push the result back
to the stack
Postfix Evaluation
Implementation Details
int prec(char c)
{
if(c == '^')
return 3;
else if(c == '*' || c == '/')
return 2;
else if(c == '+' || c == '-')
return 1;
else
return -1;
}
If the scanned character is operand
if((s[i] >= 'a' && s[i] <= 'z')||(s[i] >= 'A' && s[i] <= 'Z'))
ns+=s[i];
644
+238