Lecture - 2 - Stacks (Envy's Conflicted Copy 2016-03-03)
Lecture - 2 - Stacks (Envy's Conflicted Copy 2016-03-03)
ALGORITHMS
Lecture 2
Introduction to STACKS
Week 2
STACKS
A stack is a linear list in which insertion and deletion
take place at the same end
Thisend is called top
The other end is called bottom
Emptying a stack
STACK ADT
A linear list in which insertion and deletion take place at the same
end (i.e. top)
Elements:
Top element
Rest of Stack
Last-In-First-Out (LIFO)
Operations:
createStack()
isFull()
isEmpty()
Push()
Pop()
displayTop()
displayStack()
emptyStack()
INSERTION AND DELETION ON STACK
STACK REPRESENTATION
PUSH AND POP
Primary operations: Push and Pop
Push
Add an element to the top of the stack.
Pop
Remove the element at the top of the stack.
STACK-RELATED TERMS
Top
A pointer that points the top element in the stack.
Stack Underflow
When there is no element in the stack, the status of stack is
known as stack underflow.
Stack Overflow
When the stack contains equal number of elements as per
its capacity and no more elements can be added, the status
of stack is known as stack overflow
STACK IMPLEMENTATION
Implementation can be done in two ways
Static implementation
Dynamic Implementation
Static Implementation
Stacks have fixed size, and are implemented as arrays
It is also inefficient for utilization of memory
Dynamic Implementation
Stack grow in size as needed, and implemented as linked lists
Dynamic Implementation is done through pointers
The memory is efficiently utilize with Dynamic Implementations
STATIC IMPLEMENTATION
Linear array STACK (to store elements of stack) .
A pointer variable TOP (pointing towards the location
of top element).
TOP =0 or NULL ->indicates that stack is empty
A variable MAXSTK (giving the capacity of stack)
STATIC IMPLEMENTATION
PUSH Procedure:
PUSH(STACK, TOP, MAXSTK, ITEM)
(This procedure pushes an ITEM onto a stack)
1. [Stack already filled?]
If TOP = MAXSTK, then: Print OVERFLOW, and Return.
2. Set TOP := TOP + 1. [Increases TOP by 1]
3. Set STACK[TOP] := ITEM. [Inserts ITEM in new TOP
position]
4. Return
STATIC IMPLEMENTATION
POP Procedure:
POP(STACK, TOP, ITEM)
(This procedure deletes the top element of stack and assigns
it to the variable ITEM)
1. [Stack has an ITEM to be removed?]
If TOP = 0, then: Print UNDERFLOW, and Return.
2. Set ITEM := STACK[TOP]. [Assign TOP element to ITEM.]
3. Set TOP := TOP - 1. [Decreases TOP by 1]
4. Return
STATIC IMPLEMENTATION
Usually TOP and MAXSTK are global variables,
therefore POP and PUSH can be called using:
PUSH(STACK, ITEM)
POP(STACK, ITEM)
• STACK[TOP]= • TOP = 3 – 1= 2.
STACK[4]=WWW. • Return.
• Return.
PRACTICE PROBLEM-1
Consider the following stack of characters, where STACK is
allocated N=8 memory cells:
STACK: A,C,D,F,K,____,____,_____
Describe the stack as the following operations take place:
a) POP(STACK,ITEM)
b) POP(STACK,ITEM)
c) PUSH(STACK, L)
d) PUSH(STACK, P)
e) POP(STACK, ITEM)
f) PUSH(STACK, R)
g) PUSH(STACK, S)
h) POP(STACK, ITEM)
PRACTICE PROBLEM-2
Suppose STACK is allocated N=6 memory cells and initially
STACK is empty, or, in other words, TOP=0. Find the output of
the following module:
1. Set AAA := 2 and BBB := 5.
2. Call PUSH(STACK, AAA).
Call PUSH(STACK, 4).
Call PUSH(STACK, BBB+2).
Call PUSH(STACK, 9).
Call PUSH(STACK, AAA+BBB).
3. Repeat while TOP ≠ 0:
Call POP(STACK, ITEM).
Write: ITEM.
[End of loop.]
4. Return.
STACK Implementation Using C++
Week 2
STACK IMPLEMENTATION
Stacks can be implemented in several ways using C++:
Using Arrays
Using Linked Lists
Using Struct
Using Classes
A SAMPLE PROGRAM USING ARRAY
#include<stdio.h> switch(ch)
#include<conio.h> {
#include<stdlib.h> :case 1
#include<iostream> ;)(cout<<push
using namespace std; ;)(listStack
#define length 10 ;break
int top=-1; :case 2
int stack[length]; ;)(cout<<pop
int push();
;)(listStack
int pop();
;break
void listStack();
:case 3
void main()
;exit(0)
{
int ch;
}
do ;while(3) }
{ }
cout << endl << "1.push";
cout << endl << "2.pop";
cout << endl << "3.exit";
cout << endl << "enter choice";
cin >> ch;
A SAMPLE PROGRAM USING ARRAY
int push() )(int pop
{ {
int data; ;int tempVar
if(top+1==length) if(top==-1)
{ )(we can also make isEmpty//
cout << "stack overflow {
\n Cannot enter new data"; ;"cout << "stack is underflow (Empty)
return -1; ;return -1
} }
top++; ;tempVar=stack[top]
cout << "enter the data "; ;--top
cin >> data;
;return(tempVar)
stack[top]=data;
}
return stack[top];
)(void listStack
{
} cout << endl << "The stack is" <<
; endl
for(int i=top;i>=0;i--)
;cout << stack[i] << endl
}
A SAMPLE PROGRAM USING STRUCT
#include<stdio.h> )(void main
#include<conio.h> {
#include<stdlib.h> ;stack s
#include<iostream> ;int c; s.top=-1
do
using namespace std;
{
#define max 5 ;":cout<<"1:push\n2:pop\n3:display\n4:exit\n choice
struct stack ;cin>>c
{ switch(c)
int top, a[max]; {
}; :case 1
;push(&s)
int pop(stack *);
;break
int push(stack *); :case 2
void display(stack *p3) ;pop(&s)
{ ;break
int i; :case 3
if(p3->top==-1)
;display(&s)
;break
{
:case 4
cout<<"stack is empty\n"; ;"cout<<"pgm ends\n
return;} ;break
:default
for(i=0;i<=p3->top;i++) ;"cout<<"wrong choice\n
;break
{
}
cout<<p3->a[i]; ;while(c!=4)}
} ;)(getch
} }
A SAMPLE PROGRAM USING STRUCT
IntStack::IntStack(int size)
{
stackArray = new int[size];
stackSize = size;
top = -1;
}
PUSH() POP()
Saving local variables when one function calls another, and this
one calls another, and so on.
EXAMPLE OF STACK APPLICATIONS IN
PROGRAMMING
Converting Decimal to Binary:
Consider the following pseudocode
Read (number)
Loop (number > 0)
digit = number modulo 2
print (digit)
number = number / 2
The problem with this code is that it will print the binary number backwards. (ex: 19
becomes 11001000 instead of 00010011. ) To remedy this problem, instead of printing
the digit right away, we can push it onto the stack. Then after the number is done being
converted, we pop the digit out of the stack and print it.
ALGORITHM
1. Create STACK.
2. Read Num.
3. Repeat while NUM > 0
3.1 SET Digit := Num % 2.
3.2 If STACK is full, then:
3.2.1 Print “Stack Overflow”
3.2.2 Return.
3.3 PUSH(STACK, Digit).
3.5 SET Num := Num/2.
4. Repeat while STACK is not empty.
4.1 POP(STACK, Digit).
4.2 Write Digit.
5. Return.
EXPRESSION EVALUATION AND SYNTAX
PARSING
Many mathematical statements contain nested parenthesis
like :-
(A+(B*C) ) + (C – (D + F))
We have to ensure that the parenthesis are nested
correctly, i.e. :-
1. There is an equal number of left and right parenthesis
2. Every right parenthesis is preceded by a left
parenthesis
Expressions such as ((A + B) violate condition 1
And expressions like ) A + B ( - C violate condition 2
EXPRESSION EVALUATION AND SYNTAX
PARSING
To solve this problem, think of each left
parenthesis as opening a scope, right parenthesis
as closing a scope
Nesting depth at a particular point in an
expression is the number of scopes that have been
opened but not yet closed
Let “parenthesis count” be a variable containing
number of left parenthesis minus number of right
parenthesis, in scanning the expression from left
to right
EXPRESSION EVALUATION AND SYNTAX
PARSING
For an expression to be of a correct form following
conditions apply
Parenthesis count at the end of an expression must be 0
Parenthesis count should always be non-negative while
scanning an expression
Example :
Expr: 7 – ( A + B ) + ( ( C – D) + F )
ParenthesisCount: 0 0 1 1 1 1 0 0 1 2 2 2 2 1 1 1 0
Expr: 7 – ( ( A + B ) + ( ( C – D) + F )
ParenthesisCount: 0 0 1 2 2 2 2 1 1 23 3 3 3 2 2 21
EXPRESSION EVALUATION AND SYNTAX
PARSING
Evaluating the correctness of simple expressions like this
one can easily be done with the help of a few variables
like “Parenthesis count”
Things start getting difficult to handle by your program
when the requirements get complicated e.g.
Let us change the problem by introducing three different
types of scope de-limiters i.e. (parenthesis), {braces} and
[brackets].
In such a situation we must keep track of not only the
number of scope delimiters but also their types
When a scope ender is encountered while scanning an
expression, we must know the scope delimiter type with
which the scope was opened
We can use a stack ADT to solve this problem
EXPRESSION EVALUATION AND SYNTAX
PARSING
A stack ADT can be used to keep track of the scope
delimiters encountered while scanning the expression
Whenever a scope “opener” is encountered, it can be
“pushed” onto a stack
Whenever a scope “ender” is encountered, the stack is
examined:
If the stack is “empty”, there is no matching scope “opener” and
the expression is invalid.
If the stack is not empty, we pop the stack and check if the
“popped” item corresponds to the scope ender
If match occurs, we continue scanning the expression
When end of the expression string is reached, the stack
must be empty, otherwise one or more opened scopes
have not been closed and the expression is invalid
EXPRESSION EVALUATION AND SYNTAX
PARSING
Last scope to be opened must be the first one to be
closed.
This scenario is simulated by a stack in which the
last element arriving must be the first one to leave
Each item on the stack represents a scope that has
been opened but has yet not been closed
Pushing an item on to the stack corresponds to
opening a scope
Popping an item from the stack corresponds to
closing a scope, leaving one less scope open
.… Stack in Action
top
[ A+ { B - C + (D + E ) } ]
.… Stack in Action
top
;) ‘[‘ (Push [
[ A+ { B - C + (D + E ) } ]
.… Stack in Action
top
{
;) ‘{‘ (Push [
[ A+ { B - C + (D + E ) } ]
.… Stack in Action
top
(
{
;) ‘(‘ (Push [
[ A+ { B - C + ( D + E ) } ]
.… Stack in Action
top
(
{
;) (Pop [
[ A+ { B - C + ( D + E ) } ]
.… Stack in Action
top
{
[
[ A+ { B - C + (D + E ) } ]
.… Stack in Action
top
{
;) (Pop [
[ A+ { B - C + (D + E ) } ]
.… Stack in Action
top
[
[ A+ { B - C + (D + E ) } ]
.… Stack in Action
top
;) (Pop [
[ A+ { B - C + (D + E ) } ]
.… Stack in Action
top
[ A+ { B - C + (D + E ) } ] ]