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

DS Module 2

Good note
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

DS Module 2

Good note
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

13-07-2023

STACK
• Stack is a linear data structure which follows a particular order in
which the operations are performed.

• Stack is a LIFO (Last In First Out) structure.

• It is a linear list where all insertions and deletions are permitted only
STACK at one end of the list that is called TOP of the list.

• TOP is a pointer which points the last or top most element of Stack.

DS Module 2 • Insertion and Deletion in stack can only be done from top only.

• In a stack, when an element is added, it goes to the top of the stack.

• Definition
“Stack is a collection of similar data items in which both insertion and
deletion operations are performed based on LIFO principle”.

Stack Implementation
Operations on Stack
• Two ways
• There are two basic operations performed in a Stack:
1. Stack implementation using array.
1. Push
2. Pop 2. Stack implementation using linked list.
Overflow condition
1. Push operation is used to add or insert new
elements into the stack. That is insertion operation in Overflow occurs when we try to insert an
stack.
item into a filled stack.
2. Pop operation is used to delete or remove an Underflow condition
element from the stack. That is deletion operation in
stack. Underflow occurs during deletion that is
When a stack is completely full, it is said to be when we try to delete from empty stack.
Overflow state and if stack is completely empty, it is
said to be Underflow state.

Algorithm for Push operation-


Push Operation
Using array
• The process of putting a new data onto stack is
known as a Push Operation. • PUSH_STACK(STACK,TOP,MAX,ITEM)
• Push opera on involves a series of steps − • Algorithm to push an item into stack.
• Step 1 − Checks if the stack is full. 1) IF TOP == MAX then Print “Stack is full”;
• Step 2 − If the stack is full, produces an
error(overflow condition) and exit. Exit;
• Step 3 − If the stack is not full, increments top to 2)Otherwise TOP: = TOP + 1; /*increment TOP*/
point next empty space. STACK [TOP]:= ITEM;
• Step 4 − Adds data element to the stack loca on, 3)End of IF
where top is pointing.
• Step 5 − Returns success. 4)Exit
13-07-2023

Pop Operation Algorithm for Pop operation-


• It is used to remove an item from stack, first get the
element and then decrease TOP pointer. Using array
• In an array implementation of pop operation, the data POP_STACK(STACK,TOP,ITEM)
element is not actually removed, instead top is • Algorithm to pop an element from stack.
decremented to a lower position in the stack to point to the
next value. •
1) IF TOP == 0 then Print “Stack is empty”;
• A Pop opera on may involve the following steps − Exit;
• Step 1 − Checks if the stack is empty.
• Step 2 − If the stack is empty, produces an error (
2) Otherwise ITEM: =STACK [TOP];
underflow) and exit. TOP:=TOP – 1;
• Step 3 − If the stack is not empty, accesses the data 3) End of IF
element at which top is pointing.
• Step 4 − Decreases the value of top by 1.
4) Exit
• Step 5 − Returns success.

Linked list implementation of stack


• Instead of using array, we can also use linked list
to implement stack.
• Linked list allocates the memory dynamically.
• 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 overflow if the space left in the
memory heap is not enough to create a node.

Linked Stack Insertion


• In order to push an element onto the stack, the following steps are involved.

• Create a node first and allocate memory to it.

• 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.

• 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.
13-07-2023

Linked Stack-push operation


1.obtain a freenode
tmp=(struct node *)malloc(size of(struct node *))
2. tmp->info=item
3.if(top==NULL)
top=tmp;
tmp->link=NULL
4.Else
tmp->link=top
top=tmp
5.Return

Linked Stack Deletion


Example and Psuedocode
• In order to pop an element from the stack, we
need to follow the following steps :
– 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.
– 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.

Linked Stack-POP operation Applications of Stack


1. if top==NULL then print ”Under flow” Exit. • It can be used to process function calls.
2. else • Implementing recursive functions in high level
languages.
tmp=top • Conversion of Infix expression to Postfix expression.
item=tmp->info •Conversion of Infix expression to Prefix expression.
top=tmp->link • Evaluation of Postfix Expression.
•Checking validity of an expression containing nested
free(tmp) parenthesis.
return(item) •Reversal of a string
3.Return • Towers of Hanoi.
13-07-2023

Notations for Arithmetic Expressions Infix Notation

• In infix notation, operators are used in-between operands.


• The way to write arithmetic expression is known • e.g. a - b + c
as a notation. .
• An arithmetic expression can be written in three Prefix Notation
• In this notation, operator is prefixed to operands, i.e. operator is
different but equivalent notations, i.e., without written ahead of operands.
changing the essence or output of an expression. • For example, +ab. This is equivalent to its infix notation a + b.
• Prefix notation is also known as Polish Notation (or Prefix
• These nota ons are − Notation).
a) Infix Notation Postfix Notation
b) Prefix (Polish) Notation
• This notation style is known as Reversed Polish Notation(RPN or
c) Postfix (Reverse-Polish) Notation Suffix Notation).
• In this notation style, the operator is postfixed to the operands i.e.,
• These notations are named as how they use the operator is written after the operands.
operator in expression. • For example, ab+. This is equivalent to its infix notation a + b.

Precedence of operators ASSOCIATIVITY


Precedence • Associativity describes the rule where operators
• When an operand is in between two different with the same precedence appear in an
operators, which operator will take the operand
expression.
first, is decided by the precedence of an operator
over others. • For example, in expression a + b − c, both + and –
• For example have the same precedence, then which part of
the expression will be evaluated first, is
determined by associativity of those operators.
• Here, both + and − are le associa ve, so the
As multiplication operation has precedence over expression will be evaluated as (a + b) − c.
addition, b * c will be evaluated first.

• Precedence and associativity determines the order of


evaluation of an expression. Infix to Postfix Conversion
• Following is an operator precedence and associativity table Algorithm
(highest to lowest) −
1. Push “(“ onto stack and add “)” to the end of infix
Operator Precedence Associativity expression
1. Exponentiation ^ Highest Right Associative
2.Multiplication ( ∗ ) 2. Scan the infix expression from left to right and repeat
& Division ( / ) Second Highest Left Associative step 3-6 for each element of infix expression until the
3. Addition ( + ) stack is empty.
& Subtraction ( − ) Lowest Left Associative

• In a + b*c, the expression part b*c will be evaluated first, 3. If the scanned character is an operand, add it to
with multiplication as precedence over addition. postfix expression.
• We here use parenthesis for a + b to be evaluated first, like 4. Else if the scanned character is an “(“, push it to the
(a + b)*c. stack.
13-07-2023

5. Else if an operator ʘ is encountered, then EXAMPLE 1 Infix Expression: A+ (B*C-(D/E^F)*G)*H

5.1 Repeatedly pop all the operators from the top


of stack and add it to postfix expression which has the
same precedence or higher precedence than ʘ .
5.2 Push the scanned operator ʘ to the stack.
6. Else if the scanned character is a ‘)’, then
6.1 Repeatedly pop the stack and add the
elements to postfix expression until a ‘(‘ is encountered.
6.2 Discard both the parenthesis.
[End If]
[ End of step 2 loop]
7. Print the output postfix expression
8. Exit
Output Postfix Expression: ABC*DEF^/G*-H*+

Example 2 Advantage of Postfix Expression over


Infix Expression
• An infix expression is difficult for the machine
to know and keep track of precedence of
operators.
• On the other hand, a postfix expression itself
determines the precedence of operators (as the
placement of operators in a postfix expression
depends upon its precedence).
• Therefore, for the machine it is easier to carry
out a postfix expression than an infix
expression.

Evaluation of Postfix Expression Examples


• Let the given expression be “2 3 1 * + 9 -“. We scan all elements one by one.
Algorithm for evaluating post fix expression using stacks :-
step :- 1 start • 1) Scan ‘2’, it’s a number, so push it to stack. Stack contains ‘2’
step :- 2 for each character in the postfix expression • 2) Scan ‘3’, again a number, push it to stack, stack now contains ‘2 3’ (from
bottom to top)
step :- 3 If operand is found push it into the stack • 3) Scan ‘1’, again a number, push it to stack, stack now contains ‘2 3 1’
step :- 4 else • 4) Scan ‘*’, it’s an operator, pop two operands from stack, apply the *
step :- 5 If operator is found then pop the stack 2 times operator on operands, we get 3*1 which results in 3. We push the result ‘3’
OP2 = pop ( ) to stack. Stack now becomes ‘2 3’.
OP1 = pop ( ) • 5) Scan ‘+’, it’s an operator, pop two operands from stack, apply the +
operator on operands, we get 2+3 which results in 5. We push the result ‘5’
step :- 6 Perform the specified operation as to stack. Stack now becomes ‘5’.
result = OP1 operator OP2 • 6) Scan ‘9’, it’s a number, we push it to the stack. Stack now becomes ‘5 9’.
step :- 7 Push the intermediate result back into the stack • 7) Scan ‘-‘, it’s an operator, pop two operands from stack, apply the –
step :- 8 Repeat the above steps until the end of the expression operator on operands, we get 5 – 9 which results in -4.
• We push the result ‘-4’ to stack. Stack now becomes ‘-4’.
step :- 9 Pop the stack to obtain the final result 8) There are no more elements to scan, we return the top element from stack
step :-10 stop (which is the only element left in stack). That is -4.
13-07-2023

Example 2

• Infix Expression: (3 + 4) * (2 / 2)
• Postfix Expression: 34+22/* QUEUES
• Evaluation: 7
DS Module 2

Representation of Queues:
Queues
• Linear data structure • 1. Array representation
• FIFO structure (First In First Out) • 2.Linked list representation (Using pointers)
• 2 pointers: Front & Rear • Conditions
• 2 operations: Insertion & deletion • Overflow: rear=maxsize (rear=maxsize-1)
• Through front----deletion
• Underflow: front=0 (front=-1)
• Through rear------Insertion
• One element: front==rear!=0
• During insertion :rear=rear+1
• During deletion: front=front+1

Algorithm for Insertion using array


• QINSERT (queue,max,front,rear,item)
1. [Check whether the queue is full or not]
If rear== max:
Print overflow and return
2. Set rear=rear+1
[increase rear by 1]
3.Set queue[rear]=item
4.if front==0 (-1) then set front=front+1
[Insertion of first element in an empty queue]
5.return.
13-07-2023

Algorithm for Deletion using array Queue using Linked List


• QDELETE(queue,front,rear,item) • The elements of the queue corresponds to the
1.[Check whether the queue is empty] nodes of the linked list.
If front==NULL; Write under flow and return • Access to the first node and last node is
2. Set item=queue[front] maintained with the front pointer and rear
pointer of the queue.
3. If front==rear, then set front=rear=0
[Deletion of only one element]
4.Else set front=front+1
5.Return.

Linked Queue-Insertion Algorithm Deletion Algorithm


1.Obtain a new node. 1.If front==NULL
tmp=(struct node*)malloc(sizeof(struct node*)) print “Underflow” and return.
2.tmp->info=item 2. tmp=front
tmp->link=NULL front=tmplink
3.If front==NULL (Queue empty?)
item=tmpinfo
front=rear=tmp
4.Else free(tmp)
rear->link=tmp return(item)
rear=tmp 3.Return.
5.Return
13-07-2023

• Circular Queue –Insertion Algorithm • Circular Queue –Deletion Algorithm


1.[Circular Queue already filled?] 1.[Circular Queue already empty?]
If (front=1 and rear=N )or if front=rear+1, then If front=NULL; then write underflow and return.
write overflow and return.
2.Set item=queue[front]
2.[Find new value of rear]
If front=NULL; then[Queue initially empty] 3.[Find new value of front]
set front=1 &rear=1 If front=rear; then[Queue has only one element]
Else if rear=N &front!=1 ; then set front=NULL &rear=NULL
set rear=1 Else if front=N ; then
Else set rear=rear+1 [End of If ] set front=1
3. Set queue[rear]=item Else set front=front+1 [End of If]
4.return. 4.return.

Types of Queue
1.Normal Queue
2. Circular Queue
3.Deque
4.Priority Queue
3.DEQUE
• Stands for Double Ended Queue
• Pronounced as either “deck” or “DQ”
• It is a list in which elements can be added or removed
at either end but not in the middle.
• DQ is maintained by a circular array with LEFT(FRONT)
and RIGHT(REAR) pointers.
13-07-2023

Operation on Deque
• There are 3 basic operations on input restricted
deque
• - Insertion at rear end
• - Deletion at rear end
• - Deletion at front end
• There are 3 basic operations output restricted
deque
• - Insertion at rear end
• - Insertion at front end
• - Deletion at front end

• In this each element has been assigned a


value called the priority of the element and
the element can be inserted or deleted not
only at the ends but at any position on the
queue.

• Two types of priority queue:


– Ascending priority queue
– Descending priority queue

• In ascending priority queue elements can be


inserted in any order. Representation of Priority Queue
• But, while deleting elements from the queue
always a smallest priority element to be • 1.One way linked list
deleted first. • 2.Multiple queues, one for each priority (Using
array)
• 3. Maximum or minimum heap (using tree)
• In descending priority queue elements can be 1.One way linked list representation
inserted in any order. • In this , each node of the linked list will have
• But, while deleting elements from the queue three fields.
always a largest priority element to be deleted A. an information field INFO
first. B. a priority number PRN
C. a link field LINK
13-07-2023

• A node ‘x’ precedes a node ‘y’ in the list when ‘x’ has
higher priority than ‘y’ or when both have same
priority but ‘x ‘was inserted to the list before ‘y’.
• Priority numbers will operate in the usual way, ie the
lower the priority number, the higher the priority.
• The first element in the list is the element with
maximum priority. So it is very simple to delete an
element from priority queue.
• Adding an element to priority queue is much more
complicated. Suppose we adds an item with priority
number N to a priority queue , then
– Traverse the list until finding a node ‘x’ whose priority
number exceeds N.
– Insert the node item in front of node ‘x’.
– If no such node is found , insert item as the last node of
the list.

2. Multi-queue Implementation (Array Representation • 3. Heap representation of a priority queue


of Priority Queue)
• In multi-queue representation of priority queue, for • A heap is a complete binary tree with additional
each priority, a queue is maintained. property that the root node is either smallest or
• The queue corresponding to each priority can be highest from its children.
represented in the same array of sufficient size. • If root node of the heap is smallest from its
• In order to process an element of the priority queue, children. It is called min heap.
element from the first non empty highest priority
number queue is accessed. • If root node of the heap is largest from its
• In order to add a new element to the priority queue, children it is known as max heap.
the element is inserted in an appropriate queue for • A priority queue having highest priority for lower
given priority number.
number can be represented using min heap and a
• The first queue has highest priority number elements,
second queue has next higher priority number element priority queue having highest priority for higher
and so on. number can be represented using max heap.

You might also like