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

DS Module-2

Uploaded by

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

DS Module-2

Uploaded by

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

Data Structures and Applications(BCS304) Module 2

MODULE-2

QUEUES: Queues, Circular Queues, Using Dynamic Arrays, Multiple Stacks and queues.

LINKED LISTS : Singly Linked, Lists and Chains, Representing Chains in C, Linked
Stacks and Queues, Polynomials

Queues:
A queue is an ordered list in which insertions and deletions 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. Queues are also known as First-In-First-Out (FIFO) lists.

The ADT specification of the queue


objects: a finite ordered list with zero or more elements.
functions: for all queue∈Queue, item∈element, maxQueueSize∈ positive integer

Queue CreateQ(maxQueueSize) ::= create an empty queue whose maximum size is


maxQueueSize
BooleanIsFullQ(queue, if (number of elements in queue == maxQueueSize)
maxQueueSize) ::= returnTRUE
else returnFALSE

QueueAddQ(queue, item) ::= if (IsFullQ(queue)) queueFull


else insert item at rear of queue and return queue

BooleanIsEmptyQ(queue) ::= if (queue == CreateQ(maxQueueSize))


returnTRUE
else return FALSE

Element DeleteQ(queue) ::= if (IsEmptyQ(queue)) return


else remove and return the item at front of queue.

SHRUTHI U, Dept. of CSE(AIML), RNSIT, Bengaluru. Page 1


Data Structures and Applications(BCS304) Module 2

Example
Initially f =-1 r=-1 queue empty

Element
index [0] [1] [2] [3] [4] [5]

f=-1
Insert 3
Element 3

index [0] [1] [2] [3] [4] [5]


,r

f=-1
Insert 5
Element 3 5

index [0] [1] [2] [3] [4] [5]


r

f=-1
Insert 7
Element 3 5 7

Index [0] [1] [2] [3] [4] [5]


r

delete
Element 5 7

Index [0] [1] [2] [3] [4] [5]


F r

Deleted item =3

C implementation of queues for an integer array: A queue can be represented by using an array to
hold the elements of the array and to use two variables to hold the position of the first and last element
of the queue.

#define size 10
int q[size];
int front=-1 ,rear=-1;
SHRUTHI U, Dept. of CSE(AIML), RNSIT, Bengaluru. Page 2
Data Structures and Applications(BCS304) Module 2

 The condition where the queue is empty is called queue underflow.


 When we define the size of the array, we cannot insert elements more than the size of the array,
this condition where the queue is full is called as queue overflow.

Insert operation
The insert operation first checks for queue overflow. if the queue is not full it inserts one element into
the queue at the rear.
void insert(int item)
{
if rear==size-1)
printf(“queue overflow”);
else
{
rear++;
q[rear]=item;
}
}

Delete operation: Delete operation checks for queue underflow condition and if the queue is not
empty it will remove the element at the front.
int delete()
{
int itemdel;
if (front ==rear)
{
printf(“queue underflow”);
return(0);
}
else
{
front++
itemdel=q[front];
return(itemdel);
}
}

Display operation: The display operation will display the elements of the queue if the queue is not
empty.

void display(s)
{
if (front==rear)
printf(“queue empty”);
else
{
for(i=front+1;i<=rear;i++)
printf(“%d”,q[i]);
}
}

SHRUTHI U, Dept. of CSE(AIML), RNSIT, Bengaluru. Page 3


Data Structures and Applications(BCS304) Module 2

Disadvantage of linear queue: The following example illustrates the disadvantage of linear queue

f r Q[0] Q[1] Q[2] Q[3] Q[4] Comment


- -1 Queue is empty
-1 0 2 Insert 2
-1 1 2 3 Insert 3
-1 2 2 3 4 Insert 4
-1 3 2 3 4 5 Insert 5
-1 4 2 3 4 5 6 Insert 6
0 4 3 4 5 6 Delete- item deleted=2
1 4 4 5 6 Delete- item deleted=3
Insert 3(disadvantage)
Queue full. Element cannot
be inserted since rear= size-1

Even if the queue is empty since the value of rear= size-1 elements cannot be inserted into the queue.
This is the disadvantage of linear queue.

Circular Queue: In a circular queue the queue is arranged in a circular fashion. It is a


moreefficient representation of queue.

Example:

Fig: Implementation of circular queue for an array of integers

Modification in code to implement circular queue


 Initial value of front and rear=0
 To advance the pointer from size-1 to 0 the code rear++ is modified to rear=(rear +1)%size
and the code front++ is modified to front=(front+1)%size

SHRUTHI U, Dept. of CSE(AIML), RNSIT, Bengaluru. Page 4


Data Structures and Applications(BCS304) Module 2

 Initially when front=0 rear=0 i.e when front == rear the queue is empty now after 6 insertions
are made again fron=0 and rear= 0 that is the queue is full. So, we cannot distinguish between
an empty and a full queue.
 To avoid the resulting confusion, the value of the rear is incremented before we check for the
condition front == rear for queue overflow.

#define MAX_QUEUE_SIZE 6
int q[size];
int front=0 ,rear=0;

Insert operation: The insert operation first checks for queue overflow. if the queue is not full it inserts
one element into the queue at the rear.

void addq(element item)


{
if (front == (rear+1) % MAX_QUEUE_SIZE )
printf(“Queue full”);
else
{
rear= (rear+1) % MAX_QUEUE_SIZE
queue[rear] = item;
}
}

Delete operation: Delete operation checks for queue underflow condition and if the queue is not
empty it will remove the element at the front.

element deleteq()
{
element item;
if (front == rear)
return
queueEmpty();
front = (front+1) % MAX_QUEUE_SIZE;
return queue[front];
}

Circular Queues Using Dynamically Allocated Arrays

 To add an element to a full queue, we must first increase the size of this array using a function
such as realloc.
 As with dynamically allocated stacks, we use array doubling. However, it isn't sufficient to
simply double array size using realloc.
 Consider the full queue . This figure shows a queue with seven elements in an array whose
capacity is 8. To visualize array doubling when a circular queue is used, the array is flattened
out as shown in the array of Figure (b).

SHRUTHI U, Dept. of CSE(AIML), RNSIT, Bengaluru. Page 5


Data Structures and Applications(BCS304) Module 2

Figure (c) shows the array after array doubling by realloc.

To get a proper circular queue configuration, The number of elements copied can be limited to capacity
- 1 by customizing the array doubling code so as to obtain the configuration as shown below.

This configuration may be obtained as follows:


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

Function to add to a circular queue has no change


void addq(int item)
{
rear = (rear+1) % capacity;
if (front == (rear+1) % capacity)
queueFull(); /* double capacity */
else
{
rear = (rear+1) % capacity;
queue[rear] = item;
}
}

SHRUTHI U, Dept. of CSE(AIML), RNSIT, Bengaluru. Page 6


Data Structures and Applications(BCS304) Module 2

Function to double queue capacity


void queueFull()
{
int* newQueue;
newQueue=(int*)malloc( 2 * capacity * sizeof(int));
/* copy from queue to newQueue */
int start = (front+1) % capacity;
if (start < 2)
copy(queue+start, queue+start+capacity-1, newQueue);
else
{ /* queue wraps around */
copy(queue+start, 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;
}

The function copy(a,b,c) copies elements from locations a through b-1 to locations beginning at c

Deques: A deque (pronounced either as deck or dequeue) is a linear list in which elements
can be added or removed at either end but not in the middle. The term deque is a contraction
of the namedouble ended queue.

Representation: It is represented as a circular array deque with pointers left and right, which point to
the two ends of the queue. It is assumed that the elements extend from the left end to the right end in
the array. The term circular comes from the fact that DEQUE[0] comes after DEQUE[n-1] in the array.

Example1:
Left=2 A B C
Right=4

[0] [1] [2] [3] [4] [5] [6]

Example2:
Left=5 A B D E
Right=1
[0] [1] [2] [3] [4] [5] [6]

There are two types of deque:


 Input restricted:- insertion is allowed only at one end, deletion is allowed at both ends.
 Output restricted: deletion is allowed only at one end, insertion is allowed at both ends

SHRUTHI U, Dept. of CSE(AIML), RNSIT, Bengaluru. Page 7


Data Structures and Applications(BCS304) Module 2

Priority queue: A priority queue is a collection of elements such that each element has been
assigned a priority such that the order in which the elements are deleted and processed comes
from the following rules.
1. An element of higher priority is processed before any element of lower priority.
2. Two elements with the same priority are processed according to the order in which they were
added to the queue.

Example: Time sharing system: programs of higher priority are processed first and programs with the
same priority form a standard queue.

Representation using multiple queue: Use a separate queue for each level of priority. Each queue
will appear in its own circular array and must have its own pair of pointers, front and rear. if each
queue is allocated the same amount of space, a two dimensional array can be used instead of the linear
arrays.

Example : Consider the queue given below with the jobs and its priorities and its representation. A
job with priority 1 is considered to have the highest priority

J1 1
J2 1
J3 2
J4 4
J5 4
J6 6

The queue is represented as a two dimensional array as shown below

Front rear 1 2 3 4 5 6
1 1 2 1 J1 J2
2 2 3 2 J3
3 3
4 4 5 4 J4 J5
5 5
6 6 6 6 J6

Delete operation
Algorithm:
1. Find the smallest k such that front[k]!=rear[k] ie Find the first non empty queue
2. Delete the process at the front of the queue
3. Exit

Insert operation
Algorithm: this algorithm adds an ITEM with priority number P to a priority queue maintained by a
two dimensional array
1. Inset ITEM as the rear element in row P-1 of queue
2. exit

SHRUTHI U, Dept. of CSE(AIML), RNSIT, Bengaluru. Page 8


Data Structures and Applications(BCS304) Module 2

Multiple Stacks and Queues

 if there is a single stack, the starting point is top=-1 and maximum size is SIZE-1
 if there are two stacks to be represented in a single array then we use stack [0] for the bottom
element of the first stack, and stack[MEMORY_SIZE - 1] for the bottom element of the second
stack. The first stack grows toward stack[MEMORY_SIZE - 1] and the second grows toward
stack[0]. With this representation, we can efficiently use all the available space.
 Representing more than two stacks within the same array poses problems since we no longer
have an obvious point for the bottom element of each stack. Assuming that we have n stacks,
we can divide the available memory into n segments. This initial division may be done in
proportion to the expected sizes of the various stacks, if this is known. Otherwise, we may
divide the memory into equal segments.
 Assume that i refers to the stack number of one of the n stacks.To establish this stack, we must
create indices for both the bottom and top positions of this stack.The convention we use is that
o bottom [i], 0 ≤ i < MAX_STACKS, points to the position immediately to the left of the
bottom element of stack i.
o top[i], 0 ≤ i < MAX_STACKS points to the top element.
o Stack i is empty if bottom[i] = top[i].

The relevant declarations are:


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

To divide the array into roughly equal segments we use the following code:

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


for (j = 1; j < n; j++)
top[j] = bottom[j] = (MEMORY_SIZE/n)*j-1;
bottom[n] = MEMORY_SIZE-1;

Stack i can grow from bottom[i] + 1 to bottom [i + 1 ] before it is full. Boundary for the last stack,
boundary [n] is set to MEMORY_SIZE- 1

Initial configuration of the stack is shown below m is the size of the memory

Fig: All stacks are empty and roughly divided equally

SHRUTHI U, Dept. of CSE(AIML), RNSIT, Bengaluru. Page 9


Data Structures and Applications(BCS304) Module 2

Function to add an item to the ith stack

void push(int i, element item)


{
if (top[i] == bottom[i+1])
stackFull(i);
stack[++top[i]] = item;
}

Function to delete an item from the ith stack

element pop(int i)
{
if (top[i] == bottom[i])
return stackEmpty(i);
return stack[top[i]--];
}

Mazing Problem

Representation: Maze is represented as a two dimensional array in which zeros represent the open
paths and ones the barriers. The location in the maize can be determined by the row number and
column number Figure below shows a simple maze.

From each location there are eight directions of movement N, NE,E,SE,S,SW,W,NW.

SHRUTHI U, Dept. of CSE(AIML), RNSIT, Bengaluru. Page 10


Data Structures and Applications(BCS304) Module 2

if the position is on the border then there are less than eight directions. To avoid checking for border
conditions the maze can be surrounded by a border of ones. Thus an m*p maize will require an
(m+2)*(p+2) array the entrance is at position [1][1] and exit is at [m][p]. The possible direction to
move can be predefined in an array move as shown below where the eight possible directions are
numbered from 0 to 7. for each direction we indicate the vertical and horizontal offset.

typedef struct offset


{
int vert;
int horiz;
};

Offset move[8];

Table of moves: The array moves is initialized according to the table given below.

Name Dir Move[dir].vert Move[dir].horiz


N 0 -1 0
NE 1 -1 1
E 2 0 1
SE 3 1 1
S 4 1 0
SW 5 1 -1
W 6 0 -1
NW 7 -1 -1

As we move through the maze, we may have the choice of several directions of movement. Since we
do not know the best choice we save our current position and arbitrarily pick a possible move. By
saving the current position we can return to it and try another path. A second two dimensional array
can be maintained to keep track of the visited locations. The maze can be implemented by making use
of a stack where the element is defined as follows.

typedef struct element


{
int row;
int col;
int dir;
};

SHRUTHI U Dept. of CSE(AIML), RNSIT, Bengaluru. Page 11


Data Structures and Applications(BCS304) Module 2

Linked List
Introduction
Linked list is a collection of zero or more nodes ,where each node has some information. Given the
address of the first node, any node in the list can be obtained. Every node consis of two parts one is
the information part and the other is the address of the next node. The pointer of the last node
contains a special value called NULL.

Schematic representation of Linked List

Advantages of array representation(static allocation)


1. Data accessing is faster: Using static allocation, we can access any data element in the array
efficiently by specifying the array index for the required element. The accessing time for a[0]
is equal to a[1000].
2. Array’s are simple: Arrays are very simple to understand and it is simple to use arrays in
programming.

Disadvantages of Arrays (Static allocation)


1. Array size is fixed: In static allocation method, it is required to declare in advance the amount
of memory to be utilized.
2. The array elements are stored continuously so the size of the array cannot be increased.
3. Insertion and deletion of elements in an array is expensive as more time is spent shifting the
data.

Advantages of linked list


1. Size is not fixed
2. Data can be stored in non contiguous blocks
3. Insertion and deletion is efficient

Disadvantage of Linked List


1. More memory is required as each node stores the address of the next node
2. Difficult to access arbitrary element

SHRUTHI U Dept. of CSE(AIML), RNSIT, Bengaluru. Page 12


Data Structures and Applications(BCS304) Module 2

The different types of linear linked lists are :


1. Singly linked lists
2. Circular singly linked lists
3. Doubly linked lists
4. Circular doubly linked lists.

Representation of linked list: Each item in the list is called a node and contains two fields
 Information/Data field - The information field holds the actual elements in the list
 Link field- The Link field contains the address of the next node in the list

To create a linked list of integers the node can be defined as follows using a self referential
structure.
struct Node
{
int info;
struct Node * link;
};
typedef struct Node NODE;

After the node is created we have to create a new empty list as follows
node * first=NULL;

 The pointer first stores the address of the first node in the list. With this information we
will be able to access the location of all the other nodes in the list.
 To obtain a node we use the statement
 First=(node*) malloc(sizeof(node)
 To place the information 5 ,we can use the statement Firs->info= 5;
 As there are no other nodes in the list the link part can be made NULL as follow
 First->link=NULL

The node created is shown is represented as follows

First 5

Memory allocation and 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. Similarly a mechanism is required which makes the deleted node
available for future use.
 Together with the linked list in memory, a special list is maintained which consist 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. Such a list is also called AVAIL

SHRUTHI U Dept. of CSE(AIML), RNSIT, Bengaluru. Page 13


Data Structures and Applications(BCS304) Module 2

Instead of using the malloc function the following getnode() function can be used to get a new
node
NODE * getNode(void)
{
/* provide a node for use */NODE
* new;
if (avail)
{
new = avail;
avail = avail→link;
return new;
}
else
{
new=( NODE *)malloc(sizeof(NODE));
return new;
}
}

Instead of the free function the following retnode function can be used

void retNode(NODE *temp)


{/* return a node to the available list */
temp→link = avail;
avail = avail;
}

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, we can make this space to be available for future use.
One way is to immediately reinsert the space into the free storage list.
 This is done when a list is implemented by linear arrays. But this method may be too time
consuming for the operating system of the computer. So an alternate method is devised.
 The operating system of a computer may periodically collect all the deleted space on to the
free storage list this technique si called garbage collection

Garbage collection takes place into two steps


 Runs through all the list an marks those cells which are currently in use
 Then the computer runs through the memory collecting all unmarked space on to the free
storage list

Garbage collection takes place when


 The space is minimal or
 No space is left or
 when the CPU is idle and has time to do collection.
SHRUTHI U Dept. of CSE(AIML), RNSIT, Bengaluru. Page 14
Data Structures and Applications(BCS304) Module 2

Garbage collection is invisible to the user.


 Overflow: When new data has to be inserted in to a data structure and if there is no
available space in the free storage list , then we call this condition overflow
 Underflow: Refers to a condition when one tries to delete data from a data structure that is
empty

Operations on Linked List


Insertion into a linked list
It is assumed that the following declaration is made globally
struct Node
{
int info;
struct Node * link;
};
typedef struct Node NODE;

Function to insert a node in the front of a linked list


void insert_front( int item)
{
NODE * temp;
temp=( NODE *)malloc(sizeof(NODE);
if(temp==NULL)
{
printf("No space available\n");
exit(0);
}
else
{
temp->info=item;
temp->link=first;
first=temp;
}
}

Function to insert a node in the end of a linked list


void insert_rear(int item)
{
NODE *temp, *cur;
temp=(NODE *)malloc(sizeof(NODE));
if(temp==NULL)
{
printf("No space available\n");
exit(0);
}
temp->info=item;
SHRUTHI U Dept. of CSE(AIML), RNSIT, Bengaluru. Page 15
Data Structures and Applications(BCS304) Module 2

temp->link=NULL;
if (first==NULL)
first=temp;
else
{
cur=first
while(cur->link!=NULL)cur=cur-
>link;
cur->link=temp
}
}

Inserting an element after a node with location loc


void insert(int item, NODE* loc)
{
NODE * temp,*next;
temp=( NODE *)malloc(sizeof(NODE);
if(temp==NULL)
{
printf("No space available\n");
}
else
{
temp->info=item;
next=loc->link;
loc->link=temp;
t
emp->link=next;
}

Deletion from a linked list


Function to delete a NODE in the front of a linked list
void delete-front()
{
NODE * cur;
if (first==NULL)
printf(“List empty”);
else
{
Cur=first
first=first->link
free(cur);

}
SHRUTHI U Dept. of CSE(AIML), RNSIT, Bengaluru. Page 16
Data Structures and Applications(BCS304) Module 2

SHRUTHI U Dept. of CSE(AIML), RNSIT, Bengaluru. Page 17


Data Structures and Applications(BCS304) Module 2

Function to delete a NODE in the end of a linked list


void delete-end()
{
NODE * cur,*prev;
if (first==NULL)
printf(“List empty”);
else
if (first->link==NULL)
{
Cur=first
First=NULL
free(cur);
}
else
{
Prev=NULL;
Cur=first;
while(cur->link!=NULL)
{
Prev=cur;
Cur=cur-.link;
}
Prev->link=NULL
free(cur);
}
}

Delete the nodes from a linked list pointed by first whose information part is specified is item

NODE * delete_item(NODE *first, int item)


{
NODE *prev, *cur;
if (first==NULL)
{
printf(“list is empty”);
return(first);
}
if(first->info==item)
{
cur=first
first=first->link
free(cur);
return(first);
}
prev=NULL;
SHRUTHI U Dept. of CSE(AIML), RNSIT, Bengaluru. Page 18
Data Structures and Applications(BCS304) Module 2

cur=first;
while (cur!=NULL)
{
if (cur->info==item)
{
prev->link=cur->link;
free(cur); return(first);
}
else
{
prev=cur;
cur=cur->link;
}
}
printf(“node with item not found”)
return(first);
}

Delete the NODE present at location loc, the NODE that precedes is present at location locp. if
there is only one NODE then locp=NULL

void delete(NODE *loc, NODE*locp)


{ NODE * next;
if(locp==NULL)
{
free(Loc)
}
else
{
next=loc->link; Locp-
>link=next;free(Loc)
}
}

3.4.3 Traversal of Linked List


Function to display the contents of the list
void display(Node * first)
{
NODE *cur;

if (first==NULL)
printf(“list is empty);
else

SHRUTHI U Dept. of CSE(AIML), RNSIT, Bengaluru. Page 19


Data Structures and Applications(BCS304) Module 2

{
cur=first
while(cur!=NULL)
{
printf(“%d \t”, cur->info);cur=cur-
>link;
}
}

Function to find the length of the the list


int Length(Node * first)
{
NODE *cur;
int count=0

if (first==NULL)
{
printf(“list is empty);
return(0)
}

cur=first
while(cur!=NULL)
{
count++;
cur=cur->link;
}
return(count)
}

SEARCHING A LINKED LIST


Search an item from an unsorted list
void search(int item,struct NODE* first)
{
struct NODE *cur;if
(first==NULL)
printf(“list empty”);
else
{
cur=first;
while(cur!=NULL)
{
if(item==cur->info)
{
printf(“search successful”)
SHRUTHI U Dept. of CSE(AIML), RNSIT, Bengaluru. Page 20
Data Structures and Applications(BCS304) Module 2

retrun;
}
cur =cur->link;
}
}
printf(“search unsuccessfull”);
}

Search an item from a sorted list


void search(int item,struct NODE* first)
{
struct NODE *cur;if
(first==NULL)
printf(“list empty”);
else
{
cur=first;
while(cur!=NULL&& item>=cur->nfo)
{
if(item==cur->info)
{
printf(“search successful”)
retrun;
}
cur =cur->link;
}
}
printf(“search unsuccessfull”);
}

Additional Operations on a linked list


Function to concatenate two linked list pointed by list1 and list2
NODE* concat(struct NODE * list1,stuct NODE *list2)
{
struct NODE* temp;
if(list1==NULL)
return(list2)
if(list2==NULL)
return(list1);
temp=list1
while(temp->link!=NULL)
temp=temp->link;
temp->link=list2
return(list1)
}
SHRUTHI U Dept. of CSE(AIML), RNSIT, Bengaluru. Page 21
Data Structures and Applications(BCS304) Module 2

Function to reverse a linked list


NODE* reverse(struct NODE *first)
{
NODE *prev,*cur,*next;
cur=first;
prev=NULL;
while(cur!=NULL)
{
next= cur->link
cur->link=prev;
prev= cur;
cur=next;
}
return(prev);
}

Implementation of stack using linked list


In a stack elements are inserted and deleted at only one end. The order of insertion and deletion follows
LIFO order. To implement stack the push operation can be implemented by using insertion in front.
Pop operation can be implemented by deletion from front so that insertion and deletion is happening
at the same end.

Implementation of queue using linked list


To implement a queue using a linked list we use two pointers the front and the rear. The front pointer
will have the address of the first NODE and the rear pointer will have the address of the last NODE.
A new NODE is always attached to the rear of the list and the NODE at the front will be deleted first.
struct node
{
int info;
struct node *link;
};
typedef struct node NODE;
NODE * front,*rear;
front=NULL;
rear=NULL;

Boundary condition when front=NULL queue empty

The function inserts an element at the rear of the queue


void insert_rear(int item,NODE * rear)
{
NODE temp;
temp=(NODE*)malloc(sizeof(NODE));
if(temp==NULL)
{
SHRUTHI U Dept. of CSE(AIML), RNSIT, Bengaluru. Page 22
Data Structures and Applications(BCS304) Module 2

printf("queue overflow\n");
return(first)
}

temp->info=item;
temp->link=NULL;
if (front==NULL)
{
rear=temp;
front=temp;
}
else
{
rear->link=temp;
rear=temp;
}
}

Function deletes the NODE in the front and returns the item
int del_front(NODE * front)
{
NODE cur;int
itemdel;
if(front==NULL)
{
printf("Queue underflow\n");
return front;
}
cur=front;
itemdel=cur->info;
front=front->link;
free(cur);
return(itemdel);
}

Linked stacks and queues


 We represented stacks and queues sequentially. However, when several stacks and queues
coexisted, there was no efficient way to represent them sequentially. Fig below shows linked
stack and a linked queue.
 Notice that the direction of links for both the stack and the queue facilitate easy insertion and
deletion of NODEs. We can easily add or delete a NODE from the top of the stack. we can
easily add a NODE to the rear of the queue and delete a NODE at the front.

SHRUTHI U Dept. of CSE(AIML), RNSIT, Bengaluru. Page 23


Data Structures and Applications(BCS304) Module 2

if we wish to represent n ≤ MAX_STACKS stacks simultaneously, we begin with the


declarations:

#define MAX_STACKS 10 /* maximum number of stacks */struct


Stack
{
int data;
struct Stack * link;
};
typedef struct Stack stack stack *

top[MAX_STACKS]

We assume that the initial condition for the stacks is: top[i] = NULL, 0≤i < MAX_STACKS
and the boundary condition is: top[i] = NULL if the ith stack is empty

Function push creates a new NODE, temp, and inserts the NODE in front of the ith stack.

void push(int i, int item)


{/* add item to the ith stack */ stack *
temp; temp=(stack*)malloc(sizeof(stack))
temp→data = item;
temp→link = top[i];
top[i] = temp;
}

SHRUTHI U Dept. of CSE(AIML), RNSIT, Bengaluru. Page 24


Data Structures and Applications(BCS304) Module 2

Function pop returns the top element and changes top to point to the address contained in its
link field.

int pop(int i)
{/* remove top element from the ith stack */int
itemdel;
Stack * temp;
if (top[i]==NULL) return
stackEmpty();

temp = top[i];
itemdel = temp→data;
top[i] = top[i]→link;
free(temp);
return item;
}

To represent m ≤ MAX_QUEUES queues simultaneously, we begin with the declarations:


#define MAX_QUEUES 10 /* maximum number of queues */
struct queue {int data;
struct queue * link;
};
typedef struct queue Queue

Queue *front[MAX_QUEUES],* rear[MAX_QUEUES];

We assume that the initial condition for the queues is: front[i] = NULL, ,rear[i]=NULL0 ≤ i
< MAX_QUEUES
and the boundary condition is: front[i] = NULL iff the ith queue is empty

Function addq adds the item to the ith queue

void addq(i, item)


{/* add item to the rear of queue i */Queue *
temp;
temp= (Queue*)malloc(sizeof(Queue));
if(temp==NULL)
{
printf(“Queue Overflow”);return;
}
temp→data = item;
temp→link = NULL;
if (front[i]==NULL)

SHRUTHI U Dept. of CSE(AIML), RNSIT, Bengaluru. Page 25


Data Structures and Applications(BCS304) Module 2

{
front[i] = temp;
rear[i] = temp;
}
else
{
rear[i]→link = temp;
rear[i]=temp;

}
}

Function deleteq deletes the item in the front of the ith queue

int deleteq(int i)
{/* delete an element from queue i */Queue *
temp;
int itemdel
if (front[i]==NULL) return
queueEmpty();

temp = front[i];
itemdel = temp→data;
front[i]= front[i]→link;
free(temp);
return itemdel;
}

Circular Linked List

A singly linked list in which the last NODE has a null link is called a chain. if the link field of the
last NODE points to the first NODE in the list, then such a linked list is called a circular list.

last

By keeping a pointer at the last instead of the front we can now insert easily at the front and end of
the list

Function inserts an element to the front of the list

void insertFront(NODE *last, NODE * New)


{/* insert an item at the front of the circular list whose last NODE is last */

SHRUTHI U Dept. of CSE(AIML), RNSIT, Bengaluru. Page 26


Data Structures and Applications(BCS304) Module 2

if (last==NULL)
{
/* list is empty, change last to point to new entry */ last =
new;
last→link = last;
}
else
{
/* list is not empty, add new entry at front */
new→link = last→link;
last→link = new;
}
}

Function to insert an element in the end

void insertend(NODE *last, NODE * New)


{/* insert an item at the front of the circular list whose last NODE is last */

if (last==NULL)
{
/* list is empty, change last to point to new entry */ last =
new;
last→link = last;
}
else
{
/* list is not empty, add new entry at front */
New→link = last→link;
last→link = New;
last=New;
}
}

Function to find the length of a circular linked list

int length(NODE* last)


{/* find the length of the circular list last */NODE*
temp;
int count = 0;
if(last==NULL)
return(0);
temp = last->link /* temp is now pointing at the first NODE*/count++;
while(temp!=last)
{

SHRUTHI U Dept. of CSE(AIML), RNSIT, Bengaluru. Page 27


Data Structures and Applications(BCS304) Module 2

count++;
temp = temp→link;
}

return count;
}

Header Linked List

A header linked list is a linked list which always contains a special NODE, called the header NODE,
at the beginning of the list. There are two types of header list.

1. A grounded header list: Last NODE contains the null pointer.


2. Circular header list: Last NODE points back to the header NODE.

Note: Unless stated it is assumed that the linked list is circular header list.

Polynomials Polynomial

Representation

We should be able to represent any number of different polynomials as long as memory is available.
In general, A polynomial is represented as :
A(x)= am-1xm-1 + ............ a0x0
where the ai are nonzero coefficients and the ei are nonnegative integer exponents such that
e m-1 > em-2 >......................> e1 > e0 ≥ 0.

We represent each term as a NODE containing coefficient and exponent fields, as well as a pointer
to the next term. Assuming that the coefficients are integers, the type declarations are:

struct polyNode {int coef;

SHRUTHI U Dept. of CSE(AIML), RNSIT, Bengaluru. Page 28


Data Structures and Applications(BCS304) Module 2

int expon;
struct polyNode * link;
};
typedef struct polyNode POLY;

A polyNODE can be drawn as


coef expon link

Consider the polynomials a = 3x14 + 2x8 + 1x+2 and b = 8x12- 3x10 + 10x5 +3 It can be represented as
follows

a 3 14 2 8 1 1 2 0

b 8 12 3 10 10 5 3 0

Adding Polynomials

To add two polynomials, we examine their terms starting at the NODEs pointed to by a and b.
1. if a→expon = b→expon, we add the two coefficients a→coef + b→coef and create a new
term for the result c. a = a→link; b = b→link;
2. if a→expon < b→expon, then we create a duplicate term of b, attach this term to the
result,called c, and b = b→link;
3. if a→expon > b→expon, then we create a duplicate term of a, attach this term to the result,
called c, and a = a→link;

Adding two polynomials represented as singly Linked List

POLY *Pointer padd(POLY * a, POLY * b) /* return a polynomial which is the sum of a andb */
{
POLY * c,*tempa, *tempb,*lastc;int sum;
c= (POLY*)malloc(sizeof(POLY))c-
>link=NULL
tempa=a
tempb=blastc=c;
while (tempa!=NULL && tempb!=NULL)
{
switch (COMPARE(tempa→expon, tempb→expon))
{
case -1: lastc=attach(tempb→coef, tempb→expon,lastc);
tempb = tempb→link;
break;

SHRUTHI U Dept. of CSE(AIML), RNSIT, Bengaluru. Page 29


Data Structures and Applications(BCS304) Module 2

case 0: sum =tempa→coef + tempb→coef;


if (sum)
{
lastc=attach(sum, tempa→expon, lastc);
tempa = tempa→link; tempb = tempb→link;
}
break;
case 1: lastc=attach(tempa→coef,tempa→expon,lastc);
tema = tempa→link;
}
}

/* copy rest of list a and then list b */


while(tempa!=NULL)
{
lastc=attach (tempa→coef,tempa→expon,lastc);
tempa=tempa->link;
}
while(tempb!=NULL)
{
lastc=attach (tempb→coef,tempb→expon,lastc);
tempb=tempb->link;
}

return(c);
}

Attach a NODE to the end of a list


POLY* attach(float c, int e, POL * rear)
{
temp = (POLY*)malloc(sizeof(POLY));
temp→coef = c;
temp→expon = e;
rear->link=temp;
rear=temp;
return(rear);
}

Adding two polynomials represented as circular lists with header NODEs

POLY *Pointer padd(POLY * a, POLY * b) /* return a polynomial which is the sum of a andb */
{
POLY * c,*tempa, *tempb,*lastc;int sum;
c= (POLY*)malloc(sizeof(POLY))
c->link=c
SHRUTHI U Dept. of CSE(AIML), RNSIT, Bengaluru. Page 30
Data Structures and Applications(BCS304) Module 2

tempa=a->link;
tempb=b->link;
lastc=c;
while (tempa!=a && tempb!=b)
{
switch (COMPARE(tempa→expon, tempb→expon))
{
case -1: lastc=attach(tempb→coef, tempb→expon,lastc);
tempb = tempb→link;
break;

case 0: sum =tempa→coef + tempb→coef;


if (sum)
{
lastc=attach(sum, tempa→expon, lastc);
tempa = tempa→link; tempb = tempb→link;
}
break;
case 1: lastc=attach(a→coef,a→expon,lastc);
tempa = tempa→link;
}
}

/* copy rest of list a and then list b */


while(tempa!=a)
{
lastc=attach (a→coef,a→expon,lastc);
tempa=tempa->link;
}
while(tempb!=b)
{
lastc=attach (b→coef,b→expon,lastc);
tempb=tempb->link;
}

lastc->link=c
return(c);
}

Attach a NODE to the end of a list

POLY* attach(float c, int e, POL * rear)


{
temp = (POLY*)malloc(sizeof(POLY));

SHRUTHI U Dept. of CSE(AIML), RNSIT, Bengaluru. Page 31


Data Structures and Applications(BCS304) Module 2

temp→coef = c;
temp→expon = e;
temp->link =rear->link;
rear->link=temp;
rear=temp;
return(rear);
}

Analysis of Polynomial function


The number of non zero terms in A and in B are the most important factors in the time complexity

Therefore, let m and n be the number of nonzero terms in A and B, respectively.


A(x)= am-1xm-1 + ............ a0x0
B(x)= bm-1xn-1 + ............ b0x0

if m > 0 and n > 0, the while loop is entered. Each iteration of the loop requires O(1) time.At each
iteration, either a or b moves to the next term or both move to the next term. Since the iteration
terminates when either a or b reaches the end of the list, therefore, the number of iterations is bounded
by m + n - 1.

The time for the remaining two loops is bounded by O(n + m). The first loop can iterate m times and
the second can iterate n times. So, the asymptotic computing time of this algorithm is O(n +m).

Erasing a circular list


if we wish to compute more polynomials, it would be useful to reclaim the NODEs that are being
used. This function erases a circular list pointed by ptr and adds the NODE to the availability list.
void cerase(POLY *ptr)
{
POLY* temp;
if (ptr )
{
temp = ptr>link
ptr->link=avail
avail = temp;
*ptr = NULL;
}
}

SHRUTHI U Dept. of CSE(AIML), RNSIT, Bengaluru. Page 32

You might also like