0% found this document useful (0 votes)
31 views

Lecture - 2 - Stacks (Envy's Conflicted Copy 2016-03-03)

The document discusses stacks and their implementation in C++. It defines a stack as a linear list where insertion and deletion occur at the same end, called the top. Stacks follow the LIFO (last in, first out) principle. The key operations on a stack are push, which adds an element to the top, and pop, which removes the top element. Stacks can be implemented using arrays, linked lists, structures, or classes. Sample programs demonstrate implementing stacks using arrays, structures, and classes in C++.

Uploaded by

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

Lecture - 2 - Stacks (Envy's Conflicted Copy 2016-03-03)

The document discusses stacks and their implementation in C++. It defines a stack as a linear list where insertion and deletion occur at the same end, called the top. Stacks follow the LIFO (last in, first out) principle. The key operations on a stack are push, which adds an element to the top, and pop, which removes the top element. Stacks can be implemented using arrays, linked lists, structures, or classes. Sample programs demonstrate implementing stacks using arrays, structures, and classes in C++.

Uploaded by

Amir Sohail
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 52

DATA STRUCTURE AND

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

 Stacks are known as LIFO (Last In, First Out) lists.


 The last element inserted will be the first to be retrieved

 E.g. a stack of Plates, books, boxes etc.


OPERATION ON STACK
 Creating a stack
 Checking stack---- either empty or full

 Insert (PUSH) an element in the stack

 Delete (POP) an element from the stack

 Access the top element

 Display the elements of stack

 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)

 *NOTE: TOP is changed before insertion in PUSH but value


of TOP is changed after deletion in POP
EXAMPLE
 Consider Stack given below and simulate following operations

• PUSH(STACK, WWW) • POP(STACK, ITEM)


• Since TOP = 3, control • Since TOP = 3, control is
is transferred to Step 2. transferred to Step 2.
• TOP = 3 + 1 = 4. • ITEM = ZZZ.

• 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

int push(stack *p1) int pop(stack *p2)


{ {
;int y
int x;
if(p2->top==-1) // is Empty
if(p1->top==max-1) //stack is full {
{ ;"cout<<"stack underflow\n
cout<<"stack overflow\n"; ;return -1
}
return -1; ;y=p2->a[p2->top]
} ;p2->a[p2->top]=0
p1->top++; //incr the top ;cout<<"succ. popped\n"<<y
;--p2->top
cout<<"enter a no\n";
}
cin>>x;
p1->a[p1->top]=x; //insert element
cout<<"succ. pushed\n "<<x;
}
A SIMPLE STACK CLASS
class IntStack{
private:
int *stackArray;
int stackSize;
int top;
public:
IntStack(int);
bool isEmpty();
bool isFull();
void push();
void pop();
void displayStack();
void displayTopElement();
};
CONSTRUCTOR

IntStack::IntStack(int size)
{
stackArray = new int[size];
stackSize = size;
top = -1;
}
PUSH() POP()

void IntStack::push() void IntStack::pop()


{ {
int num; if(isEmpty()== true)
if(isFull()==true) cout<<"Stack
cout<<"stack Underflow"<<endl;
Overflow"<<endl; else
else {
{ cout<<"Number
cout<<"Enter Number="; Deleted From the
cin>>num; stack=";
top++; cout<<stackArray[top];
stackArray[top]=num; top--;
} }
} }
OTHER FUNCTIONS
bool IntStack::isEmpty() void IntStack::displayStack()
{ {
for(int i=top;i>=0;i--)
if(top==-1)
cout<<stackArray[i]<<endl;
return true; }
}
bool IntStack::isFull()
{ void IntStack::displayTopElement()
if(top>=stackSize) {
cout<<stackArray[top]<<endl;
return true;
}
}
MAIN( )
void main () switch(choice)
{ {
IntStack stack(5); case 1:
stack.push(); break;
int choice;
case 2:
do
stack.pop(); break;
{
case 3:
cout<<"Menu"<<endl;
stack.displayStack(); break;
cout<<"1-- PUSH"<<endl;
case 4:
cout<<"2-- POP"<<endl; stack.displayTopElement();
cout<<"3-- DISPLAY "<<endl; break;
cout<<"4– TOP Element"<<endl; case 5:
cout<<"5-- Exit"<<endl; break;
cout<<"Enter choice="; }
cin>>choice; }while(choice!=5);
_getch();
}
Applications of STACKS
Week 2
STACK APPLICATIONS
 “Back” button of Web Browser
 History of visited web pages is pushed onto the stack and
popped when “back” button is clicked

 “Undo” functionality of a text editor

 Reversing the order of elements in an array

 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 ) } ] ]

Result = A valid expression


RUN-TIME MEMORY MANAGEMENT

 The C++ run-time system keeps track of


the chain of active functions with a stack

 When a function is called, the run-time


system pushes on the stack a frame
containing
 Local variables and return value
 Program counter, keeping track of the
statement being executed

 When a function returns, its frame is


popped from the stack and control is
passed to the method on top of the stack
OTHER APPLICATIONS
(READING ASSIGNMENT)
 Towers of Hanoi
OTHER APPLICATIONS
(READING ASSIGNMENT)
 Bactracking
 Rearranging railroad cars

 Conversion of an Infix expression that is fully


parenthesized into a Postfix expression
 Quicksort

You might also like