You are on page 1of 59

MODULE-II

STACK, QUEUE AND


LINKED LIST

Dhakshayani. J,
Guest Faculty,
Pondicherry University.
STACK
DATA
STRUCTURE

LINEAR DATA NON LINEAR


STRUCTURE DATA
STRUCTURE

ARRAY
QUEUE STAC
K
What is Linear Data Structure
 In linear data structure, data is arranged in
linear sequence.
 Data items can be traversed in a single run.
 In linear data structure elements are accessed or
placed in contiguous(together in sequence)
memory location.
What Is Stack?
 It is an ordered group of homogeneous items of
elements.
 A stack is called a last-in-first-out (LIFO)

collection. This means that the last thing we


added (pushed) is the first thing that gets pulled
(popped) off.
 A stack is a sequence of items that are accessible

at only one end of the sequence.


Examples Of Stack:
Representation of stacks
a) Array
we have to allocate a memory block of sufficient size to
accommodate the full capacity of the stack. Then, starting from first
location of the memory block, the items of the stack can be stored in a
sequential fashion.
b) Linked List
• Although array representation is very easy and convenient, it
allows only for fixed sized stacks.
• Solution is to use single linked list which is sufficient to represent
any stack to make them dynamic.
Operations that can be performed on STACK:
PUSH POP
Function: Adds newItem to the Function: Removes topItem
top of the stack. from stack and returns it to the
item.
Preconditions: Stack has been
initialized and is not full. Preconditions: Stack has been
initialized and is not empty.
Postconditions: newItem is at
the top of the stack.. Postconditions: Top element has
been removed from stack and
item is a copy of the removed
element.
Operations – Push & Pop
PUSH : It is used to insert items into the stack.
POP: It is used to delete items from stack.
TOP: It represents the current location of data in stack.
1) Stack overflow
The condition resulting from trying to push an element onto a full
stack.
if(!stack.IsFull())
stack.Push(item);

2) Stack underflow
The condition resulting from trying to pop an empty stack.

if(!stack.IsEmpty())
stack.Pop(item);
Algorithm Of Insertion In Stack: (Push)

1. Insertion(a,top,item,max)
2. If top=max then
print ‘STACK OVERFLOW’
exit
else
3. top=top+1
end if
4. a[top]=ite
m
5. Exit
Algorithm Of Deletion In Stack: (Pop)

1. Deletion(a,top,item)
2. If t op =0 then
print ‘STACK UNDERFLOW’
exit
else
3. item=a[top]
end if
4. t o p = t o p - 1
5. Exit
Algorithm Of Display In Stack:

1.Display(top,i,a[i])
2.If t op =0 then
Print ‘STACK
EMPTY’
Exit

Else
3.Fo
r
i=t o
p to
0
APPLICATIONS OF STACKS ARE:

I. Reversing Strings:
• A simple application of stack is reversing strings. To reverse a
string , the characters of string are pushed onto the stack one by
one as the string is read from left to right.
• Once all the characters of string are pushed onto stack, they are
popped one by one. Since the character last pushed in comes
out first, subsequent pop operation results in the reversal of the
string.
For example:
To reverse the string ‘REVERSE’ the string is read
from left to right and its characters are pushed.
LIKE:
II. Checking the validity of an expression
containing nested parenthesis:

• Stacks are also used to check whether a given


arithmetic expressions containing nested parenthesis is
properly parenthesized.
• The program for checking the validity of an
expression verifies that for each left parenthesis braces or
bracket ,there is a corresponding closing symbol and
symbols are appropriately nested.
For example:
VALID INPUTS INVALID INPUTS
{} {(}
({[]}) ([(()])
{[]()} {}[])
[{({}[]({ [{)}(]}]
})}]
III. Evaluating arithmetic expressions:
• INFIX notation:
The general way of writing arithmetic
expressions is known as infix notation.
e.g, (a+b)

• PREFIX notation:
e.g, +AB

• POSTFIX notation:
e.g: AB+
Conversion of INFIX to POSTFIX conversion:
Example: (2+(4-1)*3) step1
2+41-*3 step2
2+41-3* step3
241-3*+ step4
CONVERSION OF INFIX INTO POSTFIX  No two
operators of
2+(4-1)*3 into 241-3*+ same priority can
stay together in
the stack
CURREN ACTION STACK STATUS POSTFIX
T PERFORME EXPRESSI
SYMBOL D ON
( PUSH ( (
2 2
+ PUSH + (+ 2
( PUSH ( (+( 2
4 24
- PUSH - (+(- 24
1 241
) (+(-) 241-
* PUSH * (+* 241-
3 241-3
) (+*) 2 4 1- 3 *+
IV. Tower of Hanoi problem
• Complex recursive problem
• The problem description is,
Suppose there are three pillars A,B and C. there are N
discs of decreasing size so that no two discs are of the same
size
Initially, all the discs are stacked on one pillar in their
decreasing order of size. Let this pillar be A. the other two
pillars are empty.
The problem is to move all the discs from one pillar to another using
the third pillar as an auxiliary so that,
1. Only one disc can be moved at a time.
2. A disc may be moved from any pillar to another pillar
3. At no time can a larger disc can be placed on a smaller disc
The solution of this problem can be stated recursively as follow:
Move N discs from pillar A to C via the pillar B means,
• Moving the first (N-1) discs from pillar A to B
• Moving the disc from the pillar A to C
• Moving all (N-1) discs from pillar B to C
The above solution can be described by writing a function move
(N,A,B,C)

Algorithm move (N,A,B,C)


Input: N, A,B,C
Output: Steps of moves of N discs from pillar A to B
Steps:
1. If N>0 then
2. Move (N-1,A, C, B)
3. A-> B (move from A to B)
4. Move (N-1, B, A, C)
5. Endif
6. Stop
QUEUE
What is a queue?

• It is an ordered group of homogeneous items of


elements.
• Queues have two ends:
• Elements are added at one end.
• Elements are removed from the other end.
• The element added first is also removed first
(FIFO: First In, First Out).
Example Of QUEUE:
Representation of Queue
a) Array
Q[1..N] can be used to represent a queue
Two pointers FRONT and REAR are used to indicate the two
ends of queue
INSERTION- The pointer rear will be the consultant
DELETION- the pointer front will be the consultant
Three states of a queue,
1. Queue is empty
FRONT= 0
REAR = 0 (And/ or)
2. Queue is full
FRONT= 1
REAR = N
3. Queue contains elements >= 1
FRONT <=REAR
Number of elements= REAR-FRONT+1
b) Linked list
• Limitation of queue is rigidness of its length.
• Thus we go for linked list. We select double linked list
which allow us to move both ways.
• The pointers FRONT and REAR points the first and last
node in the list.
Two states of a queue,
1. Queue is empty
FRONT= REAR = HEADER
HEADER-> RLINK= NULL
2. Queue is contains at least one element
HEADER-> RLINK != NULL
Queue Specification
Definitions: (provided by the user)
MAX_ITEMS: Max number of items that might be on the
queue
ItemType: Data type of the items on the queue

Operations
 Enqueue (ItemType, newItem)
 Dequeue (ItemType, item)
Enqueue (ItemType Dequeue (ItemType
newItem) newItem)

Function: Adds newItem Function: Removes front item


to the rear of the queue. from queue and returns it in
item.
Preconditions: Queue has Preconditions: Queue has
been initialized and is not been initialized and is not
full. empty.
Postconditions: Front element
Postconditions: newItem has been removed from queue
is at rear of queue. and item is a copy of removed
element.
1) Queue overflow
The condition resulting from trying to add an element onto a full
queue.
if(!q.IsFull())
q.Enqueue(item);

2) Queue underflow
The condition resulting from trying to remove an empty queue.

if(!q.IsEmpty())
q.Dequeue(item);
Algorithm Of Insertion In Queue: (Enqueue)

1. If REAR = MAX-1 then


write “Queue is Overflow”
Goto step 4
end if
2. if FRONT =-1 and REAR=-1
SET FRONT=REAR=0
Else
SET REAR=REAR+1
end if
3. SET QUEUE[REAR]= NUM
4. Exit
Algorithm Of Deletion In Queue: (Dequeue)

1. If FRONT =-1 or FRONT > REAR then


write “Queue is underflow”
Else
SET NUM=QUEUE [FRONT]
FRONT=FRONT+1
end if
2. Exit
Deque / Double Ended Queue

• It acts as a general representation


of both stack and queue.
• A list in which elements
can be inserted or deleted
either end
• It is also known as “Head-
Tail Linked List”
• It has two pointers LEFT
and RIGHT, which point to
end.
Dequeue can be implemented using Circular Array or a Circular
doubly linked list where Dequeue[n-1] is followed by
Dequeue[0]
Four operations of Deque
1. INSERT_FRONT(ITEM) – Insert the item at the FRONT end
of deque
2. DELETE_FRONT(ITEM)- Remove the FRONT item from a
deque
3. INSERT_REAR(ITEM) – Insert the item at the REAR end of
deque
4. DELETE_REAR(ITEM)- Remove the REAR item from a
deque
Algorithm for INSERT_FRONT(ITEM)

Step-1 : [Check for the front position]


  if(front<=1)
  Print (“Cannot add item at front end”);
  return;
 Step-2 : else
  front=front-1;
  q[front]=NUM;
 Step-3 : Return
 
Algorithm for DELETE_FRONT(ITEM)
Step-1 if front=0
  print(" Queue is Underflow”);
  return;
 Step-2 else
  NUM=q[front];
  [Set front and rear pointer]
  if front=rear
  front=0;
  rear=0;
  else
  front=front+1;
 Step-3 : Return
Algorithm for INSERT_REAR(ITEM)
Step -1: if(rear==MAX)
  Print("Queue is Overflow”);
  return;
 Step-2: else
  rear=rear+1;
  q[rear]=NUM;
  [Set rear and front pointer]
 if rear=0, then rear=1;
  if front=0, then front=1;
Step-3: return
Algorithm for DELETE_REAR(ITEM)
Step-1 : if rear=0
print(“Cannot delete value at rear end”);
return;
Step-2: else
NUM=q[rear];
[Check for the front and rear pointer]
if front= rear
front=0;
rear=0;
else
rear=rear-1;
print(“Deleted element is”, NUM);
 Step-3 : Return
Types of Deque
• Input Restricted Deque:-
In this dequeue, insertion can be done only at one of the end,
while deletion can be done from both ends.

• Output Restricted Deque:-


In this dequeue, deletion can be done only at one of the ends,
while insertions can be done on both ends
Priority Queue
• In priority queue, each element is assigned
a priority.
• Priority of an element determines the order in
which the elements will be processed.
• Element can be inserted and deleted not only at the
end but also at any position on the queue
• Rules:
1. An element with higher priority
will processed before an element
with a lower priority.
2. Two elements with the same
priority are processed on a First
Come First Serve basis.
Representation of Priority Queue

1. Using array
2. Multi queue implementation
3. Using a double linked list
1. Array representation of Priority Queue
Array hold the item and its priority value.
Insertion can be done at rear while deletion will be performed in
either of the two ways
1. traverse the array from FRONT for the element with high
priority. Delete that element from queue. If that is not the front
most element, shift all its trailing elements after deleted element
one stroke each to fill the vacant.
2. Add element at the rear end. Using stable sort
algorithm, sort the elements of queue so that the highest
priority element is at the FRONT. When the deletion is
required, delete it from FRONT end only.
2. Multi-queue implementation
This implementation assumes N different priority values.
For each Pi there are two pointers Fi and Ri.

Difficulties:
Lead to huge shifting to make room for an item to be inserted.
Large number of pointers are involved when the range of
priority values is large.
3. Linked list Representation of Priority Queue
We assumes with a node structure,

Here, all nodes are sorted according to their priority value.


Algorithm for insertion
1. Ptr=header 9. If(ptr priority >= P) then
2. New=getnode(node) Ptr1= ptr Llink
3. New data= item Ptr1 Rlink = new
4. New priority = P new Rlink = ptr
5. While( ptr Rlink != null Ptr Llink = new
and ptr priority <P) do new Llink = ptr1
6. Ptr=ptr  Rlink End if
7. End while End if
8. If (ptrRlink = null) then 10.FRONT= HEADER Rlink
ptr  Rlink =new 11.stop
new  Llink = ptr
new  Rlink = null
Rear= new
else
Algorithm for deletion
1. If(REAR=NULL) THEN 9. If(ptr priority = P) then
2. Print “Queue is empty” Ptr1= ptr Llink
3. Exit Ptr2= ptr Rlink
4. Else if(ptr = REAR)
5. ptr=REAR REAR= ptr1
6. While (ptrpriority >P and Ptr1Rlink = null
ptr!=HEADER) do else
7. ptr=ptrLlink Ptr1 Rlink = ptr2
8. End while ptr2 Llink = ptr1
9. If (ptr=HEADER) or (ptr End if
priority < P) End if
10. Print “ No item with End if
priority”,P 10. item=ptrDATA
11. Exit ReturnNode(item)
12. Else End if
11.Stop
Application of queue

1. Simulation
2. CPU scheduling in multi-programming environment
3. Round robin algorithm
1. simulation

• It is modelling of a real life problem


• Objective is to study the real life situation under the
control of various parameters which affects the real
problem. Based on the result of simulation, the actual
problem can be solved in a optimized way.
• Eg. Ticket selling centre, traffic control system
2. CPU scheduling
• Here, a single CPU has to serve more than one program
simultaneously.
• Let us consider few possible jobs for the CPU as categorized into 3
groups
1. Interrupts to be serviced
2. Interactive users to be serviced
3. Batch jobs to be serviced
3. Round robin algorithm
• RR algorithm uses the implementation of circular queue.
• Consider, N processes P1,P2..Pn required to be served by CPU.
Different process requires different execution time.
• RR algorithm first decides a small unit of time called time
quantum or time slice
• The CPU starts service P1, P1 gets the CPU for time(time
quantum) then it switches to P2 and so on. When it reaches the
end of process Pn, it returns to P1 and the same process is
repeated

Time quantum=5
In and out in a queue during RR algorithm

You might also like