0% found this document useful (0 votes)
13 views40 pages

Stack

Module 2 covers the concept of Stacks, including its definition as a linear data structure that operates on a Last-In-First-Out (LIFO) principle, along with its operations such as push, pop, and peek. It also discusses the implementation of stacks using arrays and linked lists, as well as applications like expression conversion and evaluation. Additionally, it highlights the importance of stack operations in converting infix expressions to postfix notation and evaluating them.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views40 pages

Stack

Module 2 covers the concept of Stacks, including its definition as a linear data structure that operates on a Last-In-First-Out (LIFO) principle, along with its operations such as push, pop, and peek. It also discusses the implementation of stacks using arrays and linked lists, as well as applications like expression conversion and evaluation. Additionally, it highlights the importance of stack operations in converting infix expressions to postfix notation and evaluating them.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Module 2:- Stacks

Contents
 ADT Stack and its operations: Algorithms and their complexity analysis
 Applications of Stacks: Expression Conversion and evaluation –
corresponding algorithms and complexity analysis.
 ADT queue
 Types of Queue: Simple Queue, Circular Queue, Priority Queue;
Operations on each types of Queues: Algorithms and their analysis.
ADT Stack
 The abstract datatype is special kind of datatype, whose behavior is defined
by a set of values and set of operations.
 The keyword “Abstract” is used as we can use these datatypes, we can
perform different operations. But how those operations are working that is
totally hidden from the user.
 The ADT is made of with primitive datatypes, but operation logics are
hidden.
Contd….
 A Stack is a linear data structure that follows the LIFO (Last-In-First-
Out) principle.
 Stack has one end, whereas the Queue has two ends (front and rear).
 It contains only one pointer top pointer pointing to the topmost element
of the stack.
 Whenever an element is added in the stack, it is added on the top of the
stack, and the element can be deleted only from the stack.
 a stack can be defined as a container in
In other words,
which insertion and deletion can be done from the one
end known as the top of the stack.
Some key points related to stack
 It is called as stack because it behaves like a real-world stack,
piles of books, etc.
 A Stack is an abstract data type with a pre-defined capacity,
which means that it can store the elements of a limited size.
 It is a data structure that follows some order to insert and delete
the elements, and that order can be LIFO or FILO.
Working of Stack:-
 Stack works on the LIFO pattern.
 Suppose we want to store the elements in a stack and let's assume
that stack is empty. We have taken the stack of size 5 as shown
below in which we are pushing the elements one by one until the
stack becomes full.
 Since our stack is full as the size of the stack is 5.
 In the above cases, we can observe that it goes from the top to the bottom
when we were entering the new element in the stack. The stack gets filled
up from the bottom to the top.
 When we perform the delete operation on the stack, there is only one
way for entry and exit as the other end is closed.
 It follows the LIFO pattern, which means that the value entered first will
be removed last. In the above case, the value 5 is entered first, so it will
be removed only after the deletion of all the other elements.
ADT Stack Operations
The following are some common operations implemented on the stack:
 push(): When we insert an element in a stack then the operation is known as a push. If the
stack is full then the overflow condition occurs.
 pop(): When we delete an element from the stack, the operation is known as a pop. If the
stack is empty means that no element exists in the stack, this state is known as an
underflow state.
 isEmpty(): It determines whether the stack is empty or not.
 isFull(): It determines whether the stack is full or not.'
 peek(): It returns the element at the given position.
 count(): It returns the total number of elements available in a stack.
 change(): It changes the element at the given position.
 display(): It prints all the elements available in the stack.
PUSH Operation
The steps involved in the PUSH operation is given below:
 Before inserting an element in a stack, we check whether the stack is full.
 If we try to insert the element in a stack, and the stack is full, then
the overflow condition occurs.
 When we initialize a stack, we set the value of top as -1 to check that the
stack is empty.
 When the new element is pushed in a stack, first, the value of the top gets
incremented, i.e., top=top+1, and the element will be placed at the new
position of the top.
 The elements will be inserted until we reach the max size of the stack.
POP Operation
The steps involved in the POP operation is given below:
 Before deleting the element from the stack, we check whether the stack is
empty.
 If we try to delete the element from the empty stack, then
the underflow condition occurs.
 If the stack is not empty, we first access the element which is pointed by
the top
 Once the pop operation is performed, the top is decremented by 1,
i.e., top=top-1.
Implementation/Representation of
Stack
 Array
 Linked List
Array Representation of Stack
 In array implementation, the stack is formed by using the
array.
 All the operations regarding the stack are performed using
arrays.
 Lets see how each operation can be implemented on the
stack using array data structure.
Adding an element onto the stack (push operation)

 Adding an element into the top of the stack is referred to as push


operation. Push operation involves following two steps.
1. Increment the variable Top so that it can now refer to the next memory location.

2. Add element at the position of incremented top. This is referred to as adding new
element at the top of the stack.

 Stack is overflown when we try to insert an element into a completely


filled stack therefore, our main function must always avoid stack
overflow condition.
Algorithm:
PUSH (STACK, TOP, MAXSTK, ITEM)

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. [Insert ITEM in new TOP position.]

4. Return.

Time Complexity : O(1)


Example:-
Consider the stack

XXX YYY ZZZ

1 2 3 4 5 6
7 8
TOP MAXSTK

We simulate the operation PUSH(STACK,WWW):


1. Since TOP=3, control is transferred to Step 2
2. TOP= 3+1= 4
3. STACK[TOP]=Stack[4]=WWW
4. Return

Note that WWW is now the top element in the stack.


POP (STACK, TOP, ITEM)

1. [Stack has an item to be removed?]

If TOP=0, then: Print: UNDERFLOW, and Return.

2. Set ITEM:= STACK[TOP]. [Assigns TOP element to ITEM.]

3. Set TOP:= TOP-1. [Decrease TOP by 1.]

4. Return.
Example:-
Consider the stack

1 2 3 4 5
6 7 8
TOP
MAXSTK

We simulate the operation POP(STACK,ITEM):


1. Since TOP=3, control is transferred to Step 2
2. ITEM=ZZZ.
3. TOP= 3-1= 2
4. Return
Observe that STACK[TOP]=STACK[2]=YYY is now the top element in the stack.
Visiting each element of the stack (Peek operation)
Peek operation involves returning the element which is present at the top of
the stack without deleting it. Underflow condition can occur if we try to
return the top element in an already empty stack.
PEEK (STACK, TOP, ITEM)

1. [Stack has item to be removed?]

If TOP= -1, then: Print: Stack is empty, and Return.

2. Set ITEM:= STACK[TOP]. [Assigns TOP element to ITEM.]

3. Return ITEM.

Time complexity: o(n)


Linked List implementation of Stack
 Instead of using array, we can also use linked list to implement
stack. Linked list allocates the memory dynamically.
 However, time complexity in both the scenario is same for all the
operations i.e. push, pop and peek.
 In linked list implementation of stack, the nodes are maintained
non-contiguously in the memory.
 Each node contains a pointer to its immediate successor node in
the stack.
 Stack is said to be overflown if the space left in the memory
heap is not enough to create a node.
The top most node in the stack always contains null in its address field. Lets discuss the way in which, each
operation is performed in linked list implementation of stack.
Adding a node to the stack (Push operation)
 Adding a node to the stack is referred to as push operation. Pushing an
element to a stack in linked list implementation is different from that of an
array implementation. In order to push an element onto the stack, the
following steps are involved.
1. Create a node first and allocate memory to it.
2. If the list is empty then the item is to be pushed as the start node of the list.
This includes assigning value to the data part of the node and assign null to
the address part of the node.
3. If there are some nodes in the list already, then we have to add the new
element in the beginning of the list (to not violate the property of the stack).
For this purpose, assign the address of the starting element to the address field
of the new node and make the new node, the starting node of the list.
Algorithm:-
PUSH_LINKSTACK(INFO, LINK, TOP, AVAIL, ITEM)
This procedure pushes an ITEM into a Linked Stack
1. [Available space?] If AVAIL=NULL, then Write
OVERFLOW and Exit
2. [Remove first nod from AVAIL list]
Set NEW= AVAIL and AVAIL := LINK[AVAIL].
3. Set INFO[NEW]:= ITEM [Copies ITEM into new node].
4. Set LINK[NEW]:= TOP [New node points to the original top node in the stack]
5. Set TOP := NEW [Reset TOP to point to the new node at the top o the stack]
6. Exit.
Deleting a node from the stack (POP operation)
 Deleting a node from the top of stack is referred to as pop operation.
 Deleting a node from the linked list implementation of stack is different from that
in the array implementation. In order to pop an element from the stack, we need to
follow the following steps :
1. Check for the underflow condition: The underflow condition occurs when
we try to pop from an already empty stack. The stack will be empty if the head
pointer of the list points to null.
2. Adjust the head pointer accordingly: In stack, the elements are popped only
from one end, therefore, the value stored in the head pointer must be deleted
and the node must be freed. The next node of the head node now becomes the
head node.
Time Complexity : o(n)
Display the nodes (Traversing)
 Displaying all the nodes of a stack needs traversing all the
nodes of the linked list organized in the form of stack. For this
purpose, we need to follow the following steps.
1. Copy the head pointer into a temporary pointer.
2. Move the temporary pointer through all the nodes of the list
and print the value field attached to every node.
Time Complexity : o(n)
Representation of Arithmetic
Expressions
It
is done with help of Various Notations.
Notations are:
Infix Notation
Polish Notation(Prefix)
Reverse Polish Notation(Postfix)
Expressions
1. Infix Notation: A+B, (A+B)*C
2. Polish Notation prefix:+AB,-CD
3. Reverse Polish Notation (postfix notation):
AB+,CD-,EF*,GH/
Example: infix-prefix
1.(A+B)*C
[+AB]*C
*+ABC
2. A+(B*C)
A+[*BC)
+A*BC
3.(A+B)/(C-D)
[+AB]/[-CD]
/+AB-CD
Level of Precedence

 Highest: Exponential ^
 Next Highest :Multiplication *and division /
 Lowest:Addition + and subtraction -
Important Note

 Stack converts first the expression into postfix from


infix expression .
 Secondly it evaluates the postfix expression.

…………………………..only done with the help of


stack .(so, its Application of stack in reverse order)
Evaluation of Polish Expression
 p=5,6,2,+,*,12,4,/,-
 Q=5*(6+2)-12/4

Symbol Scanned Stack


5 5
6 5,6
2 5,6,2
+ 5,8
* 40
12 40,12
4 40,12,4
/ 40,3
- 37
)
Converting Infix to Postfix Expressions
Q: A+(B*C-(D/E^F)*G)*H
Step 1:Add (and) brackets from our side to stack
Step2:Scan Q from left to right and repeat steps 3to6 for each element of Q until the stack is empty:
Step 3:if an operand is encountered ,add it to P.
Step 4: if a left parenthesis is encountered ,push onto stack .
Step 5:if an operator is encountered then:
Repeatedly pop from stack and add to P each operator (on the top of stack)which has same precedence as
or higher precedence than operator.
Add operator to stack
Step 6:if right parenthesis is encountered then :
Repeated pop from stack and add to P each operator (on the top of stack)until left parenthesis is
encountered
Remove the left Parenthesis
Step 7:exit
Symbol scanned Stack Expression P
A ( A
+ (+ A
( (+( A
B (+( AB
* (+(* AB
C (+(* ABC

- (+(- ABC*
( (+(-( ABC*

D (+(-( ABC*D

/ (+(-(/ ABC*D

E (+(-(/ ABC*DE

^ (+(-(/^ ABC*DE
F (+(-(/^ ABC*DEF

) (+(- ABC*DEF^/

* (+(-* ABC*DEF^/

G (+(-* ABC*DEF^/G

) (+ ABC*DEF^/G*-

* (+* ABC*DEF^/G*-

H (+* ABC*DEF^/G*-H

) ABC*DEF^/G*-H*+
Practice Questions

1. P:12,7,3,-,/,2,1,5,+,*,+
Ans:15
2. ((A+B)*D)^(E-F)
Ans: AB+D*EF-^

You might also like