0% found this document useful (0 votes)
44 views28 pages

DS Module2

Uploaded by

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

DS Module2

Uploaded by

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

MODULE 2: QUEUES & LINKED LISTS

QUEUES

DEFINITION
 “A queue is an ordered list in which insertions (additions, pushes) and deletions
(removals and pops) take place at different ends.”
 The end at which new elements are added is called the rear, and that from which old
elements are deleted is called the front.

If the elements are inserted A, B, C, D and E in this order, then A is the first element deleted
from the queue. Since the first element inserted into a queue is the first element removed,
queues are also known as First-In-First-Out (FIFO) lists.

QUEUE REPRESENTATION USING ARRAY

 Queues may be represented by one-way lists or linear arrays.


 Queues will be maintained by a linear array QUEUE and two pointer variables:
FRONT-containing the location of the front element of the queue
REAR-containing the location of the rear element of the queue.
 The condition FRONT = NULL will indicate that the queue is empty.

Figure indicates the way elements will be deleted from the queue and the way new elements
will be added to the queue.
 Whenever an element is deleted from the queue, the value of FRONT is increased by 1;
this can be implemented by the assignment FRONT := FRONT + 1
 When an element is added to the queue, the value of REAR is increased by 1; this can
be implemented by the assignment REAR := REAR + 1
QUEUE OPERATIONS
Implementation of the queue operations as follows.

1. Queue Create
Queue CreateQ(maxQueueSize) ::=
#define MAX_QUEUE_ SIZE 100 /* maximum queue size */
typedef struct
{
int key; /* other fields */
} element;
element queue[MAX_QUEUE_ SIZE];
int rear = -1;
int front = -1;

2. Boolean IsEmptyQ(queue) ::= front ==rear

3. Boolean IsFullQ(queue) ::= rear == MAX_QUEUE_SIZE-1

In the queue, two variables are used which are front and rear. The queue increments rear in
addq( ) and front in delete( ). The function calls would be
addq (item); and item =delete( );
4. addq(item)
void addq(element item)
{ /* add an item to the queue */
if (rear == MAX_QUEUE_SIZE-1)
queueFull();
queue [++rear] = item;
}
Program: Add to a queue

5. deleteq( )
element deleteq()
{ /* remove element at the front of the queue */
if (front == rear)
return queueEmpty( ); /* return an error key */
return queue[++front];
}
Program: Delete from a queue

6. queueFull( )
The queueFull function which prints an error message and terminates execution
void queueFull()
{
fprintf(stderr, "Queue is full, cannot add element");
exit(EXIT_FAILURE);
}

Example: Job scheduling


 Queues are frequently used in creation of a job queue by an operating system. If the
operating system does not use priorities, then the jobs are processed in the order they
enter the system.
 Figure illustrates how an operating system process jobs using a sequential representation
for its queue.

Figure: Insertion and deletion from a sequential queue


Drawback of Queue
When item enters and deleted from the queue, the queue gradually shifts to the right as shown
in figure.

In this above situation, when we try to insert another item, which shows that the queue is full .
This means that the rear index equals to MAX_QUEUE_SIZE -1. But even if the space is
available at the front end, rear insertion cannot be done.

Overcome of Drawback using different methods

Method 1:
 When an item is deleted from the queue, move the entire queue to the left so that the
first element is again at queue[0] and front is at -1. It should also recalculate rear so
that it is correctly positioned.
 Shifting an array is very time-consuming when there are many elements in queue &
queueFull has worst case complexity of O(MAX_QUEUE_ SIZE)
Method 2:

Circular Queue
 It is “The queue which wrap around the end of the array.” The array positions are
arranged in a circle.
 In this convention the variable front is changed. front variable points one position
counterclockwise from the location of the front element in the queue. The convention
for rear is unchanged.

CIRCULAR QUEUES
 It is “The queue which wrap around the end of the array.” The array positions are
arranged in a circle as shown in figure.
 In this convention the variable front is changed. front variable points one position
counterclockwise from the location of the front element in the queue. The convention
for rear is unchanged.

Implementation of Circular Queue Operations

 When the array is viewed as a circle, each array position has a next and a previous
position. The position next to MAX-QUEUE-SIZE -1 is 0, and the position that
precedes 0 is MAX-QUEUE-SIZE -1.
 When the queue rear is at MAX_QUEUE_SIZE-1, the next element is inserted at
position 0.
 In circular queue, the variables front and rear are moved from their current position to
the next position in clockwise direction. This may be done using code

if (rear = = MAX_QUEUE_SIZE-1)
rear = 0;
else rear++;
Addition & Deletion
 To add an element, increment rear one position clockwise and insert at the new position.
Here the MAX_QUEUE_SIZE is 8 and if all 8 elements are added into queue and that
can be represented in below figure (a).
 To delete an element, increment front one position clockwise. The element A is deleted
from queue and if we perform 6 deletions from the queue of Figure (b) in this fashion,
then queue becomes empty and that front =rear.
 If the element I is added into the queue as in figure (c), then rear needs to increment
by 1 and the value of rear is 8. Since queue is circular, the next position should be 0
instead of 8.
This can be done by using the modulus operator, which computes remainders.

(rear +1) % MAX_QUEUE_SIZE

void addq(element item)


{ /* add an item to the queue */
rear = (rear +1) % MAX_QUEUE_SIZE;
if (front == rear)
queueFull(); /* print error and exit */
queue [rear] = item;
}
Program: Add to a circular queue

element deleteq()
{ /* remove front element from the queue */
element item;
if (front == rear)
return queueEmpty( ); /* return an error key */
front = (front+1)% MAX_QUEUE_SIZE;
return queue[front];
}
Program: Delete from a circular queue
Note:
 When queue becomes empty, then front =rear. When the queue becomes full and
front =rear. It is difficult to distinguish between an empty and a full queue.
 To avoid the resulting confusion, increase the capacity of a queue just before it
becomes full.

CIRCULAR QUEUES USING DYNAMIC ARRAYS


 A dynamically allocated array is used to hold the queue elements. Let capacity be the
number of positions in the array queue.
 To add an element to a full queue, first increase the size of this array using a function
realloc. As with dynamically allocated stacks, array doubling is used.

Consider the full queue of figure (a). This figure shows a queue with seven elements in an
array whose capacity is 8. A circular queue is flatten out the array as in Figure (b).

Figure (c) shows the array after array doubling by relloc

To get a proper circular queue configuration, slide the elements in the right segment (i.e.,
elements A and B) to the right end of the array as in figure (d)
To obtain the configuration as shown in figure (e), follow the steps
1) Create a new array newQueue of twice the capacity.
2) Copy the second segment (i.e., the elements queue [front +1] through queue
[capacity-1]) to positions in newQueue beginning at 0.
3) Copy the first segment (i.e., the elements queue [0] through queue [rear]) to positions in
newQueue beginning at capacity – front – 1.

Below program gives the code to add to a circular queue using a dynamically allocated array.

void addq( element item)


{ /* add an item to the queue
rear = (rear +1) % capacity;
if(front == rear)
queueFull( ); /* double capacity */
queue[rear] = item;
}

Below program obtains the configuration of figure (e) and gives the code for queueFull. The
function copy (a,b,c) copies elements from locations a through b-1 to locations beginning at c.

void queueFull( )
{ /* allocate an array with twice the capacity */
element *newQueue;
MALLOC ( newQueue, 2 * capacity * sizeof(* queue));
/* copy from queue to newQueue */

int start = ( front + ) % capacity;


if ( start < 2) /* no wrap around */
copy( queue+start, queue+start+capacity-1,newQueue);
else
{ /* queue wrap around */
copy(queue, queue+capacity, newQueue);
copy(queue, queue+rear+1, newQueue+capacity-start);
}
/* switch to newQueue*/
front = 2*capacity – 1;
rear = capacity – 2;
capacity * =2;
free(queue);
queue= newQueue;
}
Program: queueFull

MULTIPLE STACKS AND QUEUES


 In multiple stacks, we examine only sequential mappings of stacks into an array. The
array is one dimensional which is memory[MEMORY_SIZE]. Assume n stacks are
needed, and then divide the available memory into n segments. The array is divided in
proportion if the expected sizes of the various stacks are known. Otherwise, divide the
memory into equal segments.
 Assume that i refers to the stack number of one of the n stacks. To establish this stack,
create indices for both the bottom and top positions of this stack. boundary[i] points to
the position immediately to the left of the bottom element of stack i, top[i] points to the
top element. Stack i is empty iff boundary[i]=top[i].

The declarations are:


#define MEMORY_SIZE 100 /* size of memory */
#define MAX_STACKS 10 /* max number of stacks plus 1 */
element memory[MEMORY_SIZE]; /* global memory declaration */
int top [MAX_STACKS];
int boundary [MAX_STACKS] ;
int n; /*number of stacks entered by the user */

To divide the array into roughly equal segments

top[0] = boundary[0] = -1;


for (j= 1;j<n; j++)
top[j] = boundary[j] = (MEMORY_SIZE / n) * j;
boundary[n] = MEMORY_SIZE - 1;
Figure: Initial configuration for n stacks in memory [m].

In the figure, n is the number of stacks entered by the user, n < MAX_STACKS, and
m =MEMORY_SIZE. Stack i grow from boundary[i] + 1 to boundary [i + 1] before it is full.
A boundary for the last stack is needed, so set boundary [n] to MEMORY_SIZE-1.
Implementation of the add operation

void push(int i, element item)


{ /* add an item to the ith stack */
if (top[i] == boundary[i+l])
stackFull(i);
memory[++top[i]] = item;
}
Program: Add an item to the ith stack

Implementation of the delete operation

element pop(int i)
{ /* remove top element from the ith stack */
if (top[i] == boundary[i])
return stackEmpty(i);
return memory[top[i]--];
}
Program: Delete an item from the ith stack

The top[i] == boundary[i+1] condition in push implies only that a particular stack ran out of
memory, not that the entire memory is full. But still there may be a lot of unused space between
other stacks in array memory as shown in Figure.
Therefore, create an error recovery function called stackFull , which determines if there is any
free space in memory. If there is space available, it should shift the stacks so that space is
allocated to the full stack.
Data Structures and Applications (15CS33)

Method to design stackFull


 Determine the least, j, i < j < n, such that there is free space between stacks j and j+1.
That is, top[j ] < boundary[j+l]. If there is a j, then move stacks i+l,i+2, .., j one position
to the right (treating memory[O] as leftmost and memory[MEMORY_SIZE - 1] as
rightmost). This creates a space between stacks i and i+1.
 If there is no j as in (1), then look to the left of stack i. Find the largest j such that 0 ≤ j
≤ i and there is space between stacks j and j+ 1 ie, top[j] < boundary[j+l]. If there is a
j, then move stacks j+l, j+2, ... , i one space to the left. This also creates space between
stacks i and i+1.
 If there is no j satisfying either condition (1) or condition (2), then all MEMORY_SIZE
spaces of memory are utilized and there is no free space. In this case stackFull terminates
with an error message.

Deepak D. Assistant Professor, Dept. of CS&E, Canara Engineering College, Mangaluru


Data Structures and Applications (15CS33)

DEFINITION
A linked list, or one-way list, is a linear collection of data elements, called nodes, where the
linear order is given by means of pointers. That is, each node is divided into two parts:
 The first part contains the information of the element, and
 The second part, called the link field or nextpointer field, contains the address of the
next node in the list.

In the above figure each node is pictured with two parts.


 The left part represents the information part of the node, which may contain an entire
record of data items.
 The right part represents the nextpointer field of the node
 An arrow drawn from a node to the next node in the list.
 The pointer of the last node contains a special value, called the null pointer, which is
any invalid address.

A pointer variable called START or FIRST which contains the address of the first node.
A special case is the list that has no nodes, such a list is called the null list or empty list and is
denoted by the null pointer in the variable START.

Deepak D. Assistant Professor, Dept. of CS&E, Canara Engineering College, Mangaluru


Data Structures and Applications (15CS33)

REPRESENTATION OF LINKED LISTS IN MEMORY

Let LIST be a linked list. Then LIST will be maintained in memory as follows.
1. LIST requires two linear arrays such as INFO and LINK-such that INFO[K] and
LINK[K] contains the information part and the nextpointer field of a node of LIST.
2. LIST also requires a variable name such as START which contains the location of the
beginning of the list, and a nextpointer sentinel denoted by NULL-which indicates the
end of the list.
3. The subscripts of the arrays INFO and LINK will be positive, so choose NULL = 0,
unless otherwise stated.

The following examples of linked lists indicate that the nodes of a list need not occupy adjacent
elements in the arrays INFO and LINK, and that more than one list may be maintained in the
same linear arrays INFO and LINK. However, each list must have its own pointer variable
giving the location of its first node.

START=9 INFO[9]=N
LINK[3]=6 INFO[6]=V
LINK[6]=11 INFO[11]=E
LINK[11]=7 INFO[7]= X
LINK[7]=10 INFO[10]= I
LINK[10]=4 INFO[4]= T
LINK[4]= NULL value, So the list has ended

Deepak D. Assistant Professor, Dept. of CS&E, Canara Engineering College, Mangaluru


Data Structures and Applications (15CS33)

REPRESENTING CHAIN IN C

The following capabilities are needed to make linked representation


1. A mechanism for defining a node’s structure, that is, the field it contains. So self-
referential structures can be used
2. A way to create new nodes, so MALLOC functions can do this operation
3. A way to remove nodes that no longer needed. The FREE function handles this
operation.

Defining a node structure

typedef struct listNode *listPointer


typedef struct {
char data[4];
listPointer list;
} listNode;

Create a New Empty list


listPointer first = NULL

To create a New Node


MALLOC (first, sizeof(*first));

To place the data into NODE


strcpy(first→ data,”BAT”);
first→ link = NULL

Deepak D. Assistant Professor, Dept. of CS&E, Canara Engineering College, Mangaluru


Data Structures and Applications (15CS33)

MEMORY ALLOCATION - GARBAGE COLLECTION

 The maintenance of linked lists in memory assumes the possibility of inserting new
nodes into the lists and hence requires some mechanism which provides unused memory
space for the new nodes.
 Mechanism is required whereby the memory space of deleted nodes becomes available
for future use.
 Together with the linked lists in memory, a special list is maintained which consists of
unused memory cells. This list, which has its own pointer, is called the list of available
space or the free storage list or the free pool.

Suppose linked lists are implemented by parallel arrays and insertions and deletions are to be
performed linked lists. Then the unused memory cells in the arrays will also be linked together
to form a linked list using AVAIL as its list pointer variable. Such a data structure will be
denoted by
LIST (INFO, LINK, START, AVAIL)

Deepak D. Assistant Professor, Dept. of CS&E, Canara Engineering College, Mangaluru


Data Structures and Applications (15CS33)

Garbage Collection
 Suppose some memory space becomes reusable because a node is deleted from a list or
an entire list is deleted from a program. So space is need to be available for future use.
 One way to bring this is to immediately reinsert the space into the free-storage list.
However, this method may be too time-consuming for the operating system of a
computer, which may choose an alternative method, as follows.

The operating system of a computer may periodically collect all the deleted space onto the
freestorage list. Any technique which does this collection is called garbage collection.
Garbage collection takes place in two steps.
1. First the computer runs through all lists, tagging those cells which are currently in use
2. And then the computer runs through the memory, collecting all untagged space onto the
free-storage list.

The garbage collection may take place when there is only some minimum amount of space or
no space at all left in the free-storage list, or when the CPU is idle and has time to do the
collection.

Overflow
 Sometimes new data are to be inserted into a data structure but there is no available
space, i.e., the free-storage list is empty. This situation is usually called overflow.
 The programmer may handle overflow by printing the message OVERFLOW. In such a
case, the programmer may then modify the program by adding space to the underlying
arrays.
 Overflow will occur with linked lists when AVAIL = NULL and there is an insertion.

Deepak D. Assistant Professor, Dept. of CS&E, Canara Engineering College, Mangaluru


Data Structures and Applications (15CS33)

Underflow
 The term underflow refers to the situation where one wants to delete data from a data
structure that is empty.
 The programmer may handle underflow by printing the message UNDERFLOW.
 The underflow will occur with linked lists when START = NULL and there is a deletion.

LINKED LIST OPERATIONS

1. Traversing a Linked list


Let LIST be a linked list in memory stored in linear arrays INFO and LINK with START
pointing to the first element and NULL indicating the end of LIST.
 Traversing algorithm uses a pointer variable PTR which points to the node that is
currently being processed.
 PTR→LINK points to the next node to be processed.
 Thus the assignment PTR= PTR→LINK moves the pointer to the next node in the list,
as pictured in below figure

Algorithm: (Traversing a Linked List) Let LIST be a linked list in memory. This algorithm
traverses LIST, applying an operation PROCESS to each element of LIST.
The variable PTR points to the node currently being processed.
1. Set PTR = START
2. Repeat Steps 3 and 4 while PTR ≠ NULL
3. Apply PROCESS to PTR→INFO
4. Set PTR = PTR→LINK
5. Exit.

Deepak D. Assistant Professor, Dept. of CS&E, Canara Engineering College, Mangaluru


Data Structures and Applications (15CS33)

The details of the algorithm are as follows.


 Initialize PTR or START.
 Then process PTR→INFO, the information at the first node.
 Update PTR by the assignment PTR = PTR→LINK, so that PTR points to the second
node. Then process PTR→INFO, the information at the second node. Again update PTR
by the assignment PTR = PTR→LINK, and then process PTR→INFO, the information
at the third node. And so on. Continue until PTR = NULL, which signals the end of the
list.

Example:
The following procedure prints the information at each node of a linked list. Since the procedure
must traverse the list.

Procedure: PRINT (INFO, LINK, START)


1. Set PTR = START.
2. Repeat Steps 3 and 4 while PTR ≠ NULL:
3. Write: PTR→INFO
4. Set PTR = PTR→LINK
5. Return.

2. Searching a Linked list


There are two searching algorithm for finding location LOC of the node where ITEM first
appears in LIST.

Let LIST be a linked list in memory. Suppose a specific ITEM of information is given.
If ITEM is actually a key value and searching through a file for the record containing ITEM,
then ITEM can appear only once in LIST.

LIST Is Unsorted
Suppose the data in LIST are not sorted. Then search for ITEM in LIST by traversing through
the list using a pointer variable PTR and comparing ITEM with the contents PTR→INFO of
each node, one by one, of LIST. Before updating the pointer PTR by
PTR = PTR→LINK
It requires two tests.
First check whether we have reached the end of the list, i.e.,
PTR == NULL
If not, then check to see whether
PTR→INFO == ITEM

Deepak D. Assistant Professor, Dept. of CS&E, Canara Engineering College, Mangaluru


Data Structures and Applications (15CS33)

Algorithm: SEARCH (INFO, LINK, START, ITEM, LOC)


LIST is a linked list in memory. This algorithm finds the location LOC of the node where
ITEM first appears in LIST, or sets LOC = NULL.
1. Set PTR: = START.
2. Repeat Step 3 while PTR ≠ NULL
3. If ITEM = PTR→INFO, then:
Set LOC: = PTR, and Exit.
Else
Set PTR: = PTR→LINK
[End of If structure.]
[End of Step 2 loop.]
4. [Search is unsuccessful.] Set LOC: = NULL.
5. Exit.

The complexity of this algorithm for the worst-case running time is proportional to the
number n of elements in LIST, and the average-case running time is approximately
proportional to n/2 (with the condition that ITEM appears once in LIST but with equal
probability in any node of LIST).

LIST is Sorted
Suppose the data in LIST are sorted. Search for ITEM in LIST by traversing the list using a
pointer variable PTR and comparing ITEM with the contents PTR→INFO of each node, one
by one, of LIST. Now, searching can stop once ITEM exceeds PTR→INFO.

Algorithm: SRCHSL (INFO, LINK, START, ITEM, LOC)


LIST is a sorted list in memory. This algorithm finds the location LOC of the node where
ITEM first appears in LIST, or sets LOC = NULL.
1. Set PTR: = START.
2. Repeat Step 3 while PTR ≠ NULL
3. If ITEM < PTR→INFO, then:
Set PTR: = PTR→LINK
Else if ITEM = PTR→INFO, then:
Set LOC: = PTR, and Exit. [Search is successful.]
Else:
Set LOC: = NULL, and Exit. [ITEM now exceeds PTR→INFO]
[End of If structure.]
[End of Step 2 loop.]
4. Set LOC: = NULL.
5. Exit.

Deepak D. Assistant Professor, Dept. of CS&E, Canara Engineering College, Mangaluru


Data Structures and Applications (15CS33)

The complexity of this algorithm for the worst-case running time is proportional to the number
n of elements in LIST, and the average-case running time is approximately proportional to n/2

3. Insertion into a Linked list

Let LIST be a linked list with successive nodes A and B, as pictured in Fig. (a). Suppose a node
N is to be inserted into the list between nodes A and B. The schematic diagram of such an
insertion appears in Fig. (b). That is, node A now points to the new node N, and node N points
to node B, to which A previously pointed.

The above figure does not take into account that the memory space for the new node N will
come from the AVAIL list.
Specifically, for easier processing, the first node in the AVAIL list will be used for the new
node N. Thus a more exact schematic diagram of such an insertion is that in below Fig.

Deepak D. Assistant Professor, Dept. of CS&E, Canara Engineering College, Mangaluru


Data Structures and Applications (15CS33)

Observe that three pointer fields are changed as follows:


1. The nextpointer field of node A now points to the new node N, to which AVAIL
previously pointed.
2. AVAIL now points to the second node in the free pool, to which node N previously
pointed.
3. The nextpointer field of node N now points to node B, to which node A previously
pointed.

There are also two special cases.


1. If the new node N is the first node in the list, then START will point to N
2. If the new node N is the last node in the list, then N will contain the null pointer.

Insertion Algorithms
Algorithms which insert nodes into linked lists come up in various situations.
1. Inserts a node at the beginning of the list,
2. Inserts a node after the node with a given location
3. Inserts a node into a sorted list.

1. Inserting at the Beginning of a List


Inserting the node at the beginning of the list.

Algorithm: INSFIRST (INFO, LINK, START, AVAIL,


ITEM)
This algorithm inserts ITEM as the first node in the list.
1. [OVERFLOW?] If AVAIL = NULL, then: Write: OVERFLOW, and Exit.
2. [Remove first node from AVAIL list.]
Set NEW: = AVAIL and AVAIL: = AVAIL→LINK
3. Set NEW→INFO:= ITEM. [Copies new data into new node]
4. Set NEW→LINK:= START. [New node now points to original first node.]
5. Set START: = NEW. [Changes START so it points to the new node.]
6. Exit.

Deepak D. Assistant Professor, Dept. of CS&E, Canara Engineering College, Mangaluru


Data Structures and Applications (15CS33)
Fig: Inserting at the Beginning of a List

Deepak D. Assistant Professor, Dept. of CS&E, Canara Engineering College, Mangaluru


Data Structures and Applications (15CS33)

2. Inserting after a Given Node


Suppose the value of LOC is given where either LOC is the location of a node A in a linked
LIST or LOC = NULL.

The following is an algorithm which inserts ITEM into LIST so that ITEM follows node A or,
when LOC = NULL, so that ITEM is the first node.

Let N denote the new node. If LOC = NULL, then N is inserted as the first node in LIST.
Otherwise, let node N point to node B by the assignment NEW→LINK:= LOC→LINK and let
node A point to the new node N by the assignment LOC→LINK:= NEW

Algorithm: INSLOC (INFO, LINK, START, AVAIL, LOC, ITEM)


This algorithm inserts ITEM so that ITEM follows the node with location LOC or inserts ITEM
as the first node when LOC = NULL.

1. [OVERFLOW?] If AVAIL = NULL, then: Write: OVERFLOW, and Exit


2. [Remove first node from AVAIL list.]
Set NEW: = AVAIL and AVAIL: = AVAIL→LINK
3. Set NEW→INFO:= ITEM [Copies new data into new node]
4. If LOC = NULL, then: [Insert as first node]
Set NEW→LINK:= START and START: = NEW.
Else: [Insert after node with location LOC]
Set NEW→LINK:= LOC→LINK and LOC→LINK:= NEW
[End of If structure.]
5. Exit.

3. Inserting into a Sorted Linked List


 Suppose ITEM is to be inserted into a sorted linked LIST. Then ITEM must be inserted
between nodes A and B so that
INFO(A) < ITEM < INFO(B)
 The following is a procedure which finds the location LOC of node A, that is, which
finds the location LOC of the last node in LIST whose value is less than ITEM.
 Traverse the list, using a pointer variable PTR and comparing ITEM with PTR→INFO
at each node. While traversing, keep track of the location of the preceding node by using
a pointer variable SAVE, as pictured in below Fig. Thus SAVE and PTR are updated by
the assignments
SAVE: = PTR and PTR: = PTR→LINK
 The traversing continues as long as PTR→INFO > ITEM, or in other words, the
traversing stops as-soon as ITEM ≤ PTR→INFO. Then PTR points to node B, so SAVE
will contain the location of the node A.

Deepak D. Assistant Professor, Dept. of CS&E, Canara Engineering College, Mangaluru


Data Structures and Applications (15CS33)

Procedure: FINDA (INFO, LINK, START, ITEM, LOC)


This procedure finds the location LOC of the last node in a sorted list such that
LOC→INFO < ITEM, or sets LOC = NULL.

1. [List empty?] If START = NULL, then: Set LOC: = NULL, and Return.
2. [Special case?] If ITEM < START→INFO, then: Set LOC: = NULL, and Return.
3. Set SAVE: = START and PTR: = START→LINK. [Initializes pointers.]
4. Repeat Steps 5 and 6 while PTR ≠ NULL.
5. If ITEM < PTR→INFO, then:
Set LOC: = SAVE, and Return.
[End of If structure.]
6. Set SAVE: = PTR and PTR: = PTR→LINK. [Updates pointers.]
[End of Step 4 loop.]
7. Set LOC: = SAVE.
8. Return.

Below algorithm which inserts ITEM into a linked list. The simplicity of the algorithm comes
from using the previous two procedures.

Algorithm: INSERT (INFO, LINK, START, AVAIL, ITEM)


This algorithm inserts ITEM into a sorted linked list.
1. [Use Procedure to find the location of the node preceding ITEM.]
Call FINDA (INFO, LINK, START, ITEM, LOC).
2. [Use Algorithm to insert ITEM after the node with location LOC.]
Call INSLOC (INFO, LINK, START, AVAIL, LOC, ITEM).
3. Exit.

3. Deletion into a Linked list

 Let LIST be a linked list with a node N between nodes A and B, as pictured in below
Fig.(a). Suppose node N is to be deleted from the linked list. The schematic diagram of
such a deletion appears in Fig.(b).
 The deletion occurs as soon as the nextpointer field of node A is changed so that it
points to node B.
 Linked list is maintained in memory in the form
LIST (INFO, LINK, START, AVAIL)

Deepak D. Assistant Professor, Dept. of CS&E, Canara Engineering College, Mangaluru


Data Structures and Applications (15CS33)

The above figure does not take into account the fact that, when a node N is deleted from our
list, immediately return its memory space to the AVAIL list. So for easier processing, it will
be returned to the beginning of the AVAIL list. Thus a more exact schematic diagram of such
a deletion is the one in below Fig.

Free storage list

Observe that three pointer fields are changed as follows:


1. The nextpointer field of node A now points to node B, where node N previously
pointed.
2. The nextpointer field of N now points to the original first node in the free pool, where
AVAIL previously pointed.
3. AVAIL now points to the deleted node N.

Deepak D. Assistant Professor, Dept. of CS&E, Canara Engineering College, Mangaluru


Data Structures and Applications (15CS33)
Deletion Algorithms
Deletion of nodes from linked lists come up in various situations.
1. Deletes the node following a given node
2. Deletes the node with a given ITEM of information.
All deletion algorithms will return the memory space of the deleted node N to the beginning
of the AVAIL list.

Deleting the Node Following a Given Node


Let LIST be a linked list in memory. Suppose we are given the location LOC of a node N in
LIST is given and location LOCP of the node preceding N or, when N is the first node, then
LOCP = NULL is given.

The following algorithm deletes N from the list.


Algorithm: DEL (INFO, LINK, START, AVAIL, LOC, LOCP)
This algorithm deletes the node N with location LOC. LOCP is the location of the node which
precedes N or, when N is the first node, LOCP = NULL.
1. If LOCP = NULL, then:
Set START: = START→LINK. [Deletes first node.]
Else:
Set LOCP→LINK:= LOC→LINK [Deletes node N.]
[End of If structure.]
2. [Return deleted node to the AVAIL list.]
Set LOC→LINK:= AVAIL and AVAIL: = LOC
3. Exit.

Deleting the Node with a Given ITEM of Information


 Consider a given an ITEM of information and wants to delete from the LIST the first
node N which contains ITEM. Then it is needed to know the location of the node
preceding N. Accordingly, first finds the location LOC of the node N containing ITEM
and the location LOCP of the node preceding node N.
 If N is the first node, then set LOCP = NULL, and if ITEM does not appear in LIST,
then set LOC = NULL.
 Traverse the list, using a pointer variable PTR and comparing ITEM with PTR→INFO
at each node. While traversing, keep track of the location of the preceding node by using
a pointer variable SAVE. Thus SAVE and PTR are updated by the assignments
SAVE:=PTR and PTR:= PTR→LINK
 The traversing continues as long as PTR→INFO ≠ ITEM, or in other words, the
traversing stops as soon as ITEM = PTR→INFO. Then PTR contains the location LOC
of node N and SAVE contains the location LOCP of the node preceding N

Deepak D. Assistant Professor, Dept. of CS&E, Canara Engineering College, Mangaluru


Data Structures and Applications (15CS33)

Procedure: FINDB (INFO, LINK, START, ITEM, LOC, LOCP)


This procedure finds the location LOC of the first node N which contains ITEM and the
location LOCP of the node preceding N. If ITEM does not appear in the list, then the
procedure sets LOC = NULL; and if ITEM appears in the first node, then it sets LOCP =
NULL.
1. [List empty?] If START = NULL, then:
Set LOC: = NULL and LOCP: = NULL, and Return.
[End of If structure.]
2. [ITEM in first node?] If START→INFO = ITEM, then: Set
LOC: = START and LOCP = NULL, and Return.
[End of If structure.]
3. Set SAVE: = START and PTR: = START→LINK. [Initializes pointers.]
4. Repeat Steps 5 and 6 while PTR ≠ NULL.
5. If PTR→INFO = ITEM, then:
Set LOC: = PTR and LOCP: = SAVE, and Return.
[End of If structure.]
6.Set SAVE: = PTR and PTR: = PTR→LINK. [Updates pointers.] [End
of Step 4 loop.]
7. Set LOC: = NULL. [Search unsuccessful.]
8. Return.

Deepak D. Assistant Professor, Dept. of CS&E, Canara Engineering College, Mangaluru

You might also like