Sei sulla pagina 1di 11

ADT STACK

Linear Data Structures


Are collections of items arranged in a straight line (i.e. in array, or maybe. . .linked list!)
Stacks and Queues are linear data structures, where data can be stored linearly!
However:
o Some rules are applied when adding and removing items from Stacks and Queues.
Stacks
A stack is a container where the last item added (pushed) must comes out first (popped)
So it is a Last in First Out, LIFO
The Stack Structure
Like any other structure, stacks need to be created, hence the formal operation CREATE
Activation of a stack is usually accomplished by initializing the Top pointer to NULL. A stack
may grow and then decrease until it is again empty as though freshly activated. The formal
operation that checks the validity of a stack is EMPTY
A stack grows if a single node is inserted into its Top position. The formal operation that inserts a
node into a stack is PUSH
The only value of a stack that is accessible to its environment is the value of its Top node. The
only reactivable value of a stack is that of its Top node. The formal operation that returns the
value of its Top node is TOP
The Top node must be removed from a stack before the values of other nodes can be retrieved.
The formal operation that removes the Top node from a stack is DELETE
Stacks may be implemented by Create, Empty, Insert (Push), Delete and Top, and their
interaction. Top followed by Delete implemented as one operation is called POP
Characteristics of stacks:
A stack can resequence a string of entries
A stack is immediate; entry and exits from a stack are first operations. What you get is what you
see on top.
Data can only be placed on the top of the stack.
Data can only be removed from the top of the stack.
Data can only be removed from the bottom of the stack if there is only one item on the stack.
Data can not be removed from the middle of the stack without first removing all items from the
top.
ADT Stack Applications
Stacks in languages
o Key to call / return in functions and procedures
o Stack frame allows recursive calls
o Call- push stack frame, return pop stack frame
o Stack frame
Function arguments
Return address
Local variables
Reversing Data: We can use stacks to reverse data. (example: files, strings)
o By placing the characters on the stack in the order read, the first character read will be the
last written.
o User types: a b c d

Converting Decimal to Binary


1

Evaluating arithmetic expressions.

Stack Behaviors
The behavior of putting an item on the stack is called push.
The behavior of removing and item from the stack is called pop.
Example
What stack exists after executing the following commands?
o push(3)
o push(6)
o push(8)
o push(1)
o pop()
o pop()
o push(14)
Arithmetic Expressions
Arithmetic expressions have
o Operands (variables or numeric constants).
o Operators
Binary : +, -, *, / ,%
Unary: Priority convention:
o Unary minus (sign for negative numbers) has highest priority
o *, /, %
have medium priority
o +, have lowest priority
Infix, Prefix, Postfix
Consider two case studies that relate to evaluating arithmetic expressions
o Postfix and infix notation
Expressions normally written in infix form
o Binary operations inserted between their operands
A computer normally scans an expression string in the order that it is input; easier to evaluate an
expression in postfix form
Example: arithmetic expression a & b consists of operands a, b and operator &.
o Infix notation is format where operator is specified in between the two operands. a&b
o Prefix notation is format where operator is specified before the two operands. & a b
o Postfix notation is format where operator is specified after the two operands. Postfix
notation is also called RPN or Reverse Polish Notation. a b &
Advantage of postfix form is that there is no need to group subexpressions in parentheses
No need to consider operator precedence
Arithmetic Expressions
Prefix Notation

Infix Notation

Postfix Notation

+A * B C

A+B*C

ABC*+

* +AB C

(A+B) * C

AB+C*

+ AB C

AB+C

ABC+

A+ B C

A (B+C)

ABC+
2

Boolean Expressions
Boolean expressions have
o Operands (variables of boolean type or boolean constants TRUE, FALSE).
o Operators
Binary : &, V, =>,
Unary:
~
Convention for operator priorities:
o ~ has highest priority,
o & has next priority level,
o v has next priority level,
o => has next priority level,
o has lowest priority.
Infix, Prefix, Postfix for Boolean Expressions
Example: Boolean expression a & b consists of operands a, b and operator &.
o Infix notation is format where operator is specified in between the two operands. a&b
o Prefix notation is format where operator is specified before the two operands. & a b
o Postfix notation is format where operator is specified after the two operands. Postfix
notation is also called RPN or Reverse Polish Notation. a b &
Boolean Expressions
Prefix Notation
vA& B C
& v AB C
v &A B C
& Av B C

Infix Notation
AvB& C
(AvB) & C
A& BvC
A & (BvC)

Postfix Notation
ABC& v
ABvC&
AB& Cv
ABCv&

Evaluating Arithmetic Expressions in Postfix Notation


Algorithm:
o INPUT: list of tokens that are either numbers or binary arithmetic operators +, -,*, /, and
%. List represents postfix notation of an arithmetic expression
o OUTPUT: value of expression.
To evaluate the postfix expression, it is necessary to:
o Create an empty stack that will contain operands.
o Take one by one token from the left to right.
If token is an operand push it to the stack.
If token is an operator op
Pop the top item from the stack as operand2.
Pop again the top item from the stack as operand1.
Perform operation operand1 op operand2.
Push result back to stack.
When all tokens in input expression are processed stack should contain a single item, which is
the value of expression.
Note:
1. An operator in a postfix expression applies to the two operands that immediately precede it. Thus
the operand most recently entered is retrieved first.
2. Each time you enter an operand, the calculator pushes it onto a stack. When you enter an
operator, the calculator applies it to the top two operands from the stack, and then pushes the
result of the operation onto the stack.
Pseudo code algorithm that evaluates postfix expression
For (each character Ch in the string) {
3

If (Ch is an operand)
Push value that operand Ch represents onto a stack
Else //Ch is an operator named Op
{
//Evaluate and push the result
Operand1 = top of stack
Pop the stack
Operand2 = top of stack
Pop the stack
Result = Operand1 Op Operand2
Push result onto stack
}
//end if
}//end for
Example 1: Evaluate 5 6 * 10 -

Example 2: Evaluate 3 2 - 4 *
Current Token Stack Content After Processing the
Token (Top is at the right side)
3
3
2
32
1
4
*

14
4

What was done


Push 3
Push 2
Pop 2 as second operand, pop 3 as first operand, 32 is 1. Push 1.
Push 4
Pop 4 as second operand, pop 1 as first operand,
1*4 is 4. Push 4.

Exercise:
Evaluate the following postfix expressions:
1) 1 2 3 + * (Ans 5)
2) A * (B + C) When A = 2, B = 3 and C = 4 (Postfix ABC + *) (Ans 14)
3) ABC++ when A =1, B = 2, C = 3 (Ans 6)
4) A + (B - C)* D When A = 7, B= 3, C = 12, D = -5 (Postfix ABC D*+) (Ans 52)
Evaluating Boolean Expressions in Postfix Notation
Algorithm is same as for arithmetic expressions:
o INPUT: list of tokens that are either TRUE or FALSE or operators &, V, =>, . List
represents postfix notation of an arithmetic expression.
4

o OUTPUT: value of expression that is either TRUE or FALSE.


Create an empty stack that will contain boolean operands.
o Take one by one token from the left to right.
If token is an operand push it to the stack.
If token is an operator op
Pop the top item from the stack as operand2.
Pop again the top item from the stack as operand1.
Perform operation operand1 op operand2.
Push result back to stack.
o When all tokens in input expression are processed stack should contain a single item,
which is the boolean value of expression.

Evaluate:
True True & False =>
Current Token Stack Content After
Processing the Token
(Top is at the right side)
True
True
True
True True
&
True
False
=>

True False
False

What was done


Push True
Push True
Pop True as second operand, pop True as first operand,
True&True is true. Push True.
Push False
Pop False as second operand, pop True as first operand,
True =>False is False. Push False onto stack.

CONVERTING INFIX EXPRESSIONS TO EQUIVALENT POSTFIX EXPRESSIONS


The following are facts about converting from infix to postfix
a) The operands always stay in the same order with respect to one another
b) An operator will move only to the right with respect to the operands i.e. if, in the infix
expression, the operand X precedes the operator Op, it also true that in the postfix expression, the
operand X precedes the operator Op
c) All parentheses are removed
Parentheses, operator precedence and left to right association determine where to place operators in the
postfix expression.
Note:
1. When assigning precedence, the highest is always exponential function, level two multiplication
and division, level one addition and subtraction
2. A further assumption is that operators in the same level of precedence are to be evaluated from
left to right
Algorithm to Convert an Infix Expression to Postfix
Accepts:
An infix expression
o
Convert the expression to POSTFIX
o
Uses a stack to store operations
Output:
The POSTFIX expression
INFIX EXPRESSION TO POSTFIX
Initialize an empty stack of operators.
While no error has occurred and the end of the infix expression has not been reached, do the
following
5

a) Get the next input Token (constant, variable, arithmetic operator, left and right parenthesis) in the
infix expression.
b) If Token is
i)
a left parenthesis:
Push it onto the stack
ii)
a right parenthesis: Pop and display stack elements until a left parenthesis is
popped, but do not display it.
(It is an error if the stack becomes empty with no left parenthesis
found.)
iii)
an operator:
If the stack is empty or Token has a higher priority than the top
stack, push Token onto the stack. Otherwise, pop and display the
top stack element: then repeat the comparison of Token with the
new top stack item.
A left parenthesis in the stack is assumed to have a lower priority
than that of operators. This step orders the operators by precedence
and in accordance with left-to-right association.
iv)
an operand:
Display it.
c) When the end of the infix expression is reached, pop and display stack items until the stack is
empty
Example 1: Convert x1 + 2.5 * count /3 to Postfix

Example 2: Convert A + B * C - D / E to postfix


Infix
StackS(bot>top)
Postfix
a)A+B*CD/E
b)+B*CD/E
A
c)B*CD/E
+
A
d)*CD/E
+
AB
e)CD/E
+*
AB
f)D/E
+*
ABC
g)D/E
+
ABC*
h)/E
+
ABC*D
i)E
+/
ABC*D
j)
+/
ABC
*DE
Example
3: Convert A * B - ( C + D ) + E to postfix
k)
ABC*D
E/+

Infix

Stack(bot>top) Postfix
A*B(CD)+E
*B(C+D)+E
B(C+D)+E
(C+D)+E
(C+D)+E
(C+D)+E
C+D)+E
+D)+E
D)+E
)+E
+E
+E
E

empty
empty
*
*
empty

(
(
(+
(+

empty
+
+
empty

empty
A
A
AB
AB*
AB*
AB*
AB*C
AB*C
AB*CD
AB*CD+
AB*CD+
AB*CD+
AB*CD+E
AB*CD+E+
7

Example 4:
Convert infix expression into postfix (7+1)*(6+ (3-2)) >> POSTFIX

TOKEN

Stack After (Top is on the right)

(+

(+

71

Display

71+

71+

*(

71+

*(

71+6

*(+

71+6

*(+(

71+6

*(+(

71+63

*(+(-

71+63

*(+(-

71+63

*(+

71+63-

71+63-+

7 1 + 6 3 - + displayed
o Stack content *
Add that to display
o 7 1 + 6 3 - + * is POSTFIX

Exercise
Convert the following infix expressions to postfix:
a) 7-(2*3+5)*(8-4/2) (Ans 723*5+842/-*- )
b) A- ( B + C * D ) / E
c) A + (B * C / D) * E
d) B + C * D
e) A * (B / C / D) + E
Balancing Parentheses in Infix Notation
Example
a * ( b + c ) (( a + b ) / c))
The number of left parentheses must be equal to the number of right parentheses
Checking Parentheses
Create an empty stack
Until a special symbol appears (indicating the end of expression) do
Read one by one token from the input expression
If token is{
If the stack is empty push token to the stack
8

If the stack is non empty pop a top stack element


If the popped element is ( or [ type an error message such as Rule 2 is not
satisfied at position
Otherwise push it back and push the token to the stack.
[

If the stack is empty rule 1 is not satisfied. Type a message

If the stack is not empty pop the top stack element and
If it is { then read next token
Otherwise type Rule 1 is not satisfied at position
]

Other Skip to the next token


If the stack is non empty after the end of expression has been encountered then print an error
message such as Rule 1 is violated at the end of expression
else
Check control is O.K.
Summary
1. Stack behavior is that of LIFO collection
2. Like a list, it is dynamic , increasing with insertion and decreasing with deletion
3. Unlike a list, inserted items can only be reached by repeated removal of the top item. A stack
does not require a traversal
4. In all its forms, a stack is managed by create, push (insert), delete and top

LAB PROGRAMMING EXERCISE: STACKS


//Stack implementation as a class
#include<iostream.h>
#include<process.h>
#include<conio.h>
#define SIZE 20
class stack{
int a[SIZE];
int tos; // Top of Stack
public:
stack();
void push(int);
int pop();
int isempty();
int isfull();
};
//Constructor
stack::stack(){
tos=0;
}

//Initialize Top of Stack

int stack::isempty(){
return (tos==0?1:0);
}
9

int stack::isfull(){
return (tos==SIZE?1:0);
}
void stack::push(int i){
if(!isfull()){
a[tos]=i;
tos++;
}
else{
cerr<<"Stack overflow error ! Possible Data Loss !";
}
}
int stack::pop(){
if(!isempty()){
return(a[--tos]);
}
else
{
cerr<<"Stack is empty! What to pop...!";
}
return 0;
}
void main(){
stack s;
int ch=1,num;
while(ch!=0){
cout<<"Stack Operations Main Menu\n1.Push\n2.Pop\n3.IsEmpty\n4.IsFull\n0.Exit\n";
cin>>ch;
switch(ch){
case 0:
exit(1); //Normal Termination of Program
case 1:
cout<<"Enter the number to push"<<endl;;
cin>>num;
s.push(num);
break;
case 2:
cout<<"Number popped from the stack is: "<<s.pop()<<endl;
break;
case 3:
(s.isempty())?(cout<<"Stack is empty."):(cout<<"Stack is not empty.");
break;
case 4:
(s.isfull())?(cout<<"Stack is full."):(cout<<"Stack is not full.");
break;
default:
10

cout<<"Illegal Option.Please try again"<<endl;


}
}//end of while
getch();
}

11

Potrebbero piacerti anche