DSA Chapter 8 Stack
DSA Chapter 8 Stack
STACK
2
Introduction to Stack
l Stack is a collection of items
which is organized in a
sequential manner.
l Example: stack of books or
stack of plates.
l All additions and deletions
are restricted at one end,
called top.
l LAST IN FIRST OUT (LIFO)
data structure.
SCSJ 2013 3
Example of Stack
l Long and narrow driveway
– BMW comes in first, Lexus follows, Benz enters in
last.
– When the cars come out, Benz comes out first, then
Lexus follows, and BMW comes out last.
l Reverse a string
Example: TOP , Reverse: POT
l Brackets balancing in compiler
l Page-visited history in a Web browser
l Undo operation in many editor tools
l Check nesting structure
SCSJ 2013 4
More Example: undo operation
l In an Excel file, input your data in row
– 100, 200, 300, 400
l Find something wrong, use undo, return to previous
state
Operation lists
SCSJ 2013 5
What Is Stack?
l Stack is an abstract data type
l Adding an entry on the top is called push
l Deleting an entry from the top is called pop
l A stack is open at one end only(the top). You can
push entry onto the top, or pop the top entry out of the
stack.
SCSJ 2013 6
Last-in First-out (LIFO)
SCSJ 2013 7
Stack implementation
SCSJ 2013 8
Implementation for Stack
Array
l Size of stack is fixed during declaration
l Item can be pushed if there is some space available,
need isFull( ) operations.
l Need a variable called, top to keep track the top of a
stack.
l Stack is empty when the value of Top is –1.
Linked List
l Size of stack is flexible. Item can be pushed and
popped dynamically.
l Need a pointer, called top to point to top of stack.
SCSJ 2013 9
Array Implementation of Stack
Stack Operations:
l createStack()
l push(item) top = 2
l pop( )
l isEmpty( )
l isFull( ) “Stack can be visualized as
array, BUT the operations
l stackTop() can be done on top stack
only. “
SCSJ 2013 10
Push() and pop() operations
stack stack
empty empty
SCSJ 2013 11
Array Implementation of Stack
3 things to be considered for stack with array
1. Stack Empty : when top is -1.
2. Push operations: To insert item into stack
2 statements must be used
top = top + 1;
stack[top] = newitem;
3. pop operations: To delete item from stack.
2 statements should be used
Item = stack[top]; or stackTop();
top = top – 1;
l Item = stack[top]; statement is needed if we
want to check the value to be popped.
SCSJ 2013 12
Array Implementation of Stack
Stack declaration:
const int size = 100;
class stack
{
private : // data declaration
int top ;
char data[size] ;
public : // function declaration
void createStack();
void push(char) ; // insert operation
void pop() ; // delete operation
char stackTop() ; // get top value
bool isFull() ; // check if stack is Full
bool isEmpty(); // check if stack is empty
} ;
SCSJ 2013 13
Array Implementation of Stack
l We need two data attributes for stack:
1. Data : to store item in the stack, in this
example data will store char value
2. top : as index for top of stack, integer type
l Size of the array that store component
of stack is 100. In this case, stack can
store up to 100 char value.
l Declaration of stack instance:
stack aStack;
SCSJ 2013 14
Array Implementation of Stack
createStack() operation
l Stackwill be created by initializing top to -1.
l createStack() implementation:
SCSJ 2013 15
Array Implementation of Stack
isFull() Operation
l This operation is needed ONLY for implementation of stack using array.
l In an array, size of the array is fixed and to create new item in the array
will depend on the space available.
l This operation is needed before any push operation can be implemented
on a stack.
l bool isFull() implementation
bool stack::isFull()
{
return (top == size-1 );
}
SCSJ 2013 16
Array Implementation of Stack
bool isEmpty() operation
l This operation will check whether the array for stack is
empty.
l This operation is needed before ANY pop operation can be
done. If the stack is empty, then pop operation cannot be
done.
l bool isEmpty() will return true if top –1 and return false
if top is not equal to -1, showing that the stack has element
in it.
l bool isEmpty()implementation :
bool stack::isEmpty()
{
return ( top == -1 );
}
SCSJ 2013 17
Array Implementation of Stack
push(newItem) operation : Insert item onto stack
l push() operation will insert an item at the top of stack. This operation
can be done only if there is space availbale in the array
l Before any item can be inserted into a stack, isFull() operation must be
called first.
l Insertion operation involve the following steps:
l Top will be increased by 1.
top = top + 1;
l New item will be inserted at the top
data[Top] = newItem;
SCSJ 2013 18
Array Implementation of Stack
void stack::push(char newitem)
{
if (isFull()) // check whether stack is full
cout << “Sorry,Cannot push item.
Stack is now full!"<< endl;
else
{ top = top + 1 // Top point to next index
data[top] = newitem; //assign new item at top
}//end else
}//end push()
SCSJ 2013 19
Array Implementation of Stack
pop()Operation
l Thisoperation will delete an item at top of scak.
l Function isEmpty() will be called first in orderto
ensure that there is item in a stack to be deleted.
l pop() operation will decrease the value of top by 1:
top = top - 1;
SCSJ 2013 20
Array Implementation of Stack
void stack::pop()
{
char item;
if ( isEmpty() )
cout << “Sorry, Cannot pop item.
Stack is empty!” << endl;
else
{ //display value at top to be deleted
cout << “Popped value :” << data[top];
top = top – 1;
// top will hold to new index
}// end if
}//end pop
SCSJ 2013 21
Array Implementation of Stack
stackTop()operation : to get value at the top
char stackTop()
{ //function to get top value
if (isEmpty())
cout <<“Sorry, stack is empty!”<< endl;
else
return data[top];
} // end stackTop
SCSJ 2013 22
Linked List Implementation of Stack
l Stack implemented using linked list – number of
elements in stack is not restricted to any size.
l Dynamic memory creation, memory will be assigned to
stack when a new node is pushed into stack, and
memory will be released when an element being
popped from the stack.
l Stack using linked list implementation can be empty or
contains a series of nodes.
l Each node in a stack must contain at least 2 attributes:
l i) data – to store information in the stack.
l ii) pointer next (store address of the next node in the
stack
SCSJ 2013 23
Linked List Implementation of Stack
Basic operations for a stack implemented using linked
list:
l createStack() – initialize top
l push(char) – insert item onto stack
l pop() – delete item from stack
l isEmpty() – check whether a stack is empty.
l stackTop() – get item at top
SCSJ 2013 24
Linked List Implementation of Stack:
push() and pop() operations
Create stack
SCSJ 2013 25
Linked List Implementation of Stack
class nodeStack
{
int data;
nodeStack *next;
};
class stack
{
private: // pengisytiharan ahli data
nodeStack *top;
public : // pengisytiharan ahli fungsi
void createStack(); // set Top to NULL
void push(int) ; // insert item into stack
void pop() ; // delete item from stack
int stackTop() ; // get content at top stack
bool isEmpty(); // check whether stack is empty
};
SCSJ 2013 26
Create Stack and isEmpty()
l Creating a stack will initialize top to NULL - showing
that currently, there is no node in the stack.
void stack::createStack()
{
top = NULL;
}
bool stack::isEmpty()
{
return (top == NULL);
}
SCSJ 2013 27
push() operations
SCSJ 2013 28
push() to empty stack
SCSJ 2013 29
push()to non-empty stack
This operation is similar to inserting element in front of a
linked list. The next value for the new element will point
to the top of stack and head will point to the new
element.
SCSJ 2013 30
Push() operations
void stack::push(int newitem)
{ // create newnode
nodeStack *newnode;
newnode = new (nodeStack);
if( newnode == NULL)
cout << “Cannot allocate memory…” << endl;
else // add to empty stack, or to front stack
{ newnode->data = newitem;
newnode->next = head;
head = newnode;
}// end if
} //end push operation
SCSJ 2013 31
Delete item from stack (pop)
l Pop operation can only be done to non-empty stack. Before pop()
operation can be done, operation must be called in order to check
whether the stack is empty or there is item in the stack. If isEmpty()
function return true, pop() operation cannot be done.
l During pop() operation, an external pointer is needed to point to the
delete node. In the figure below, delnode is the pointer variable to point
to the node that is going to be deleted.
SCSJ 2013 32
Pop() operation
void stack::pop()
{ nodeStack *delnode;
if (isEmpty())
cout <<“Sorry, Cannot pop item from
stack.Stack is still empty!” <<endl;
else
{ delnode = head;
cout << “Item to be popped from stack
is: ” << stackTop()<<endl;
head = delnode->next;
delete(delnode);
}// end else
} // end pop
SCSJ 2013 33
Check item at top stack
int stack::stackTop()
{ if (isEmpty())
cout <<“Sorry,Stack is still empty!”
<<endl;
else
return head->data;
} // end check item at top
SCSJ 2013 34
End of Stack Implementation
What we have learned so far….
l Stack is a LIFO data structure
l Can be implemented using array and link list
l Structure of a stack using array and link list
l Basic Operation for a stack
l createStack(),push(),pop()
l stackTop(),isEmpty(),isFull()
SCSJ 2013 35
Next…..Stack Application
SCSJ 2013
Stack Application Examples
SCSJ 2013 37
Example1:
Parantheses Balance
l Stack can be used to recognize a balanced
parentheses.
l Examples of balanced parentheses.
(a+b), (a/b+c), a/((b-c)*d)
Open and closed parentheses are properly
paired.
l Examples of not balance parentheses.
((a+b)*2 and m*(n+(k/2)))
Open and closed parentheses are not
properly paired.
SCSJ 2013 38
Check for Balanced Parantheses
Algorithm
create (stack);
continue = true;
while ( not end of input string) && continue
{ ch = getch( );
if ch = ‘(’ || ch = ‘)’
{ if ch = ‘(’
Push(stack, ‘(’);
else if IsEmpty(stack)
continue = false;
else
Pop(s);
} // end if
} // end while
if ( end of input && isEmpty(stack);
cout << “Balanced..” << end1;
else
cout << “Not Balanced.. ” << endl;
SCSJ 2013 39
Check for Balanced Parantheses
Algorithm
SCSJ 2013 40
Example for Balance Parantheses
l Example 2: A+B*C
l To evaluate infix expression,
the following rules were applied:
1. Precedence rules.
2. Association rules (associate from left to right)
3. Parentheses rules.
SCSJ 2013 44
Prefix and Postfix Expressions
l Alternatives to infix expression
l Prefix : Operator appears before its operand.
l Example:
l Postfix
: Operator appears after its operand.
l Example:
SCSJ 2013 45
Infix, prefix and postfix
SCSJ 2013 46
Converting Infix to Prefix
Steps to convert infix expression to prefix:
STEP 2
SCSJ 2013 47
Converting Infix to Prefix
Another Example:
SCSJ 2013 48
Converting Infix to Postfix
STEP 1
STEP 2
SCSJ 2013 49
Converting Infix to Postfix
SCSJ 2013 50
Evaluating Postfix Expression
l Postfix expression can be evaluated easily
using stack.
l Stack operations, such as push(), pop() and
isEmpty() will be used to solve this problem.
l Steps to evaluate postfix expression :
1. Convert infix to postfix expression.
2. Evaluate postfix using stack.
SCSJ 2013 51
Converting Infix to Postfix Algorithm
52
Converting Infix to Postfix Algorithm
if (ch is an operator)
{ while (!isEmpty(s) &&
(precedence(stacktop()) >= precedence(ch)))
{ chpop = pop(s);
add chpop to postfix notation;
}
push(s, ch);
}
} // end while
while (stacktop() != ‘#’)
{ ch = pop(s);
add ch to postfix notation;
}// end while
SCSJ 2013 53
Converting Infix to Postfix
A+B*C–D/E
infix stack postfix
SCSJ 2013 54
Converting Infix to Postfix :
A * B – ( C + D )+ E
INFIX STACK POSTFIX
A*B–(C+D)+E #
*B–(C+D)+E # A
B– (C+D)+E #* A
– (C+D)+E #* AB
(C+D)+E #- AB*
C+D)+E #-( AB*
+D)+E #-( AB*C
D)+E #-(+ AB*C
)+E #-(+ AB*CD
+E #- AB*CD+
E #+ AB*CD+-
#+ AB*CD+-E
# AB*CD+-E+
55
Steps to Evaluate Postfix Expression
1. If char read from postfix expression is an operand, push
operand to stack.
2. If char read from postfix expression is an operator, pop the first
2 operand in stack and implement the expression using the
following operations:
l pop(opr1) dan pop(opr2)
l result = opr2 operator opr1
l Finally, At the end of the operation, only one value left in the
stack. The value is the result of postfix evaluation.
SCSJ 2013 56
Evaluating Postfix Expression
SCSJ 2013 57
Evaluating Postfix Expression :
246+*
Postfix Ch Opr Opn1 Opn2 Result Stack
2 4 6 + *
4 6 + * 2 2
6 + * 4 2 4
+ * 6 2 4 6
* + + 6 4 10 2 10
* * 10 2 20 20
SCSJ 2013 58
Evaluating Postfix Expression :
2 7 * 18 - 6 +
postfix result stack
2 2
SCSJ 2013 59
Thank You
60