BCS304-DSA Notes M-2
BCS304-DSA Notes M-2
BCS304-DSA Notes M-2
2.1 QUEUES
“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.
Page 1
DATA STRUCTURES AND APPLICATIONS (BCS304)
Page 2
DATA STRUCTURES AND APPLICATIONS (BCS304)
Example:
Elements 10, 20, 30, 40 and 50 i entered into queue as in Fig. 2.4.
Page 3
DATA STRUCTURES AND APPLICATIONS (BCS304)
Example:
Initially, rear points to -1. So when queue is empty, rear should point to -1 and front
should point to 0 (Fig 2.6(a)). Elements are deleted from the front end. For example,
delete 10, 20, 30, 40 and 50 from the queue in the fig. 2.4 will result in the queue in the
fig.2.6(b). When front>rear it results empty queue. Hence we need to make the initial
condition as front=0 and rear = -1 when front>rear.
Page 4
DATA STRUCTURES AND APPLICATIONS (BCS304)
Page 5
DATA STRUCTURES AND APPLICATIONS (BCS304)
Page 6
DATA STRUCTURES AND APPLICATIONS (BCS304)
When the array is viewed as a circle, each array position has a next and a previous
position. The position next to position MAX-1 is 0,and the position that precedes
0 is MAX-1,the next element is put into position 0.
To work with the circular queue, we must be able to move the variables front and
rear from their current position to the next position(clockwise).
If front =-1 and rear =-1 we cannot distinguish between queue empty and
queuefull. To avoid this confusion we set front=0 and rear =0 in circular queue.
Page 7
DATA STRUCTURES AND APPLICATIONS (BCS304)
Page 8
DATA STRUCTURES AND APPLICATIONS (BCS304)
}
}
Delete Function
void delete()
{
if(front==rear)
{
printf(“ Circular Queue underflow”);
return;
}
else
{
front=(front+1)%MAX;
printf(“\n deleted element is %d”,q[front]);
}
}
Page 9
DATA STRUCTURES AND APPLICATIONS (BCS304)
void display()
{
int i;
if(front==rear)
{
printf(“circular queue is empty\n”);
}
else
{
printf(“\n contents of circular queue”);
for(i=(front+1)%MAX ;i!=rear;i=(i+1)%MAX)
{
printf(“%d\t”,q[i]);
}
printf(“%d\t”,q[i]);
}
}
Page 10
DATA STRUCTURES AND APPLICATIONS (BCS304)
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.
Page 11
DATA STRUCTURES AND APPLICATIONS (BCS304)
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 + 1 ) % capacity; if ( start < 2)
/* no wrap around */
copy( queue+start, queue+start+capacity-1,newQueue);
else
{
/* queue wrap around */
copy(queue+start, queue+capacity, newQueue);
copy(queue, queue+rear+1, newQueue+capacity-start); }
Page 12
DATA STRUCTURES AND APPLICATIONS (BCS304)
/* switch to newQueue*/
front = 2*capacity – 1;
rear = capacity – 2;
capacity * =2;
free(queue);
queue= newQueue;
}
Page 13
DATA STRUCTURES AND APPLICATIONS (BCS304)
Example:
Page 14
DATA STRUCTURES AND APPLICATIONS (BCS304)
Page 15
DATA STRUCTURES AND APPLICATIONS (BCS304)
Page 16
DATA STRUCTURES AND APPLICATIONS (BCS304)
equal amount of space bounded by indices b[i] and e[i]. This is shown in Fig.
2.14(b)
Page 17
DATA STRUCTURES AND APPLICATIONS (BCS304)
Page 18
DATA STRUCTURES AND APPLICATIONS (BCS304)
Page 19
DATA STRUCTURES AND APPLICATIONS (BCS304)
Page 20
DATA STRUCTURES AND APPLICATIONS (BCS304)
Page 21
DATA STRUCTURES AND APPLICATIONS (BCS304)
void create()
{
printf("\n enter the no of elements to be inserted into the list\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
Page 22
DATA STRUCTURES AND APPLICATIONS (BCS304)
2.Insert to Front
It works same as create function, by inserting new node to front. Here only one node can
be inserted at a time.
Program code for insert front operation
void insert_front()
{
Page 23
DATA STRUCTURES AND APPLICATIONS (BCS304)
3.Insert to End
Suppose we have empty list, then first is equal to NULL. Then directly create new node
and make it as first. But suppose we have list as in Fig.1. Now if we want to perform
insert end, then new node to be attached to right side of the last node (right of 10 here).
Create a new node and name it as temp and read new data(30) to temp as in Fig.3. Check
if lastlink=NULL and if it is not equal to NULL make last=lastlink and
lastlink=NULL as in Fig.3 and then connect new node ‘temp’ to ‘lastlink’ as in
Fig.3.
Page 24
DATA STRUCTURES AND APPLICATIONS (BCS304)
Page 25
DATA STRUCTURES AND APPLICATIONS (BCS304)
}
4.Delete from Front
Suppose if we want to delete a node from front from the Fig.3, (delete node contains data
20), then make ‘temp’ as ‘first’ and delete tempdata and make ‘templink’ as ‘first’. If
first=NULL, then that means there is no element in the list.
Page 26
DATA STRUCTURES AND APPLICATIONS (BCS304)
free(first);
first=NULL;
}
else
{
while(temp->link!=NULL)
{
last=temp;
temp=temp->link;
}
last->link=NULL;
printf("Deleted element is %d\n",temp->data);
free(temp); // delete last node
}
return;
}
Page 28
DATA STRUCTURES AND APPLICATIONS (BCS304)
Figure 3.9.3 shows the algorithm to push an element into a linked stack. In Step 1,
memory is allocated for the new node. In Step 2, the DATA part of the new node
is initialized with the value to be stored in the node. In Step 3, we check if the new
node is the first node of the linked list. This is done by checking if TOP = NULL.
In case the IF statement valuates to true, then NULL is stored in the NEXT part of
Page 30
DATA STRUCTURES AND APPLICATIONS (BCS304)
the node and the new node is called TOP. However, if the newnode is not the first
node in the list, then it is added before the first node of the list (that is, the TOP
node) and termed as TOP.
Page 31
DATA STRUCTURES AND APPLICATIONS (BCS304)
void pop()
{
if(top == NULL)
printf("\nStack is overflow!!!\n");
else
{
struct Node *temp = top;
printf("\nDeleted element: %d", temp->data);
top = temp->next;
free(temp);
}
}
void display()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else
Page 33
DATA STRUCTURES AND APPLICATIONS (BCS304)
{
struct Node *temp = top;
while(temp->next != NULL)
{
printf("%d--->",temp->data);
temp = temp -> next;
}
printf("%d--->NULL",temp->data);
}
}
2.8 Linked Queue
We have seen how a queue is created using an array. Although this technique of
creating a queue is easy, its drawback is that the array must be declared to have
some fixed size.
If we allocate space for 50 elements in the queue and it hardly uses 20–25
locations, then half of the space will be wasted. And in case we allocate less
memory locations for a queue that might end up growing large and large, then a lot
of re-allocations will have to be done, thereby creating a lot of overhead and
consuming a lot of time.
In case the queue is a very small one or its maximum size is known in advance,
then the array implementation of the queue gives an efficient implementation.
But if the array size cannot be determined in advance, the other alternative ,i.e.
the linked representation is used.
In a linked queue, every element has two parts, one that stores the data and
another which holds the address of the next element. The START pointer of the
linked list is used as FRONT. Here we will also use another pointer called REAR,
which will store the address of the last element in the queue. All insertions will be
done at the rear end and all the deletions will be done at front end. If
FRONT=REAR=NULL, then it indicates that the queue is empty. The linked
representation of queue is shown in Fig. 3.10.1.
Page 34
DATA STRUCTURES AND APPLICATIONS (BCS304)
The insert operation is used to insert an element into the queue. The new element
is added as the last element of the queue. Consider the linked queue shown in Fig.
3.10.2 (a). To insert an element with value 9, we first check if FRONT=NULL. If
this is the case, then we allocate memory for a new node, store the value in its
DATA part and NULL in its NEXT part. The new node will then be called
FRONT and REAR. However, if FRONT! =NULL, then we insert the new node
at the rear end of the linked queue and name this new node as REAR. Thus, the
updated stack becomes as shown in Fig. 3.10.2(b).
Delete Operation
The delete operation is used to delete the element that is first inserted
Page 35
DATA STRUCTURES AND APPLICATIONS (BCS304)
The delete operation is used to delete the element that is first inserted into the
queue. i.e. the element whose address is stored at FRONT.
However, before deleting the value, we must first check if FRONT=NULL,
because if this is the case, then it means that the queue is empty and no more
deletions can be done. If an attempt is made to delete a value from a stack that is
already empty, an UNDERFLOW message is printed.
Consider the stack shown in Fig. 3.10.4(a). To delete an element, we first check if
FRONT=NULL. If it is false, then we delete the 1st node pointed by the FRONT.
The FRONT will now point to the 2nd element of the linked queue. Thus the
updated queue becomes as shown in Fig. 3.10.4(b).
Page 36
DATA STRUCTURES AND APPLICATIONS (BCS304)
PTR that points to FRONT. In Step 3, FRONT is made to point to the next node in
sequence. In Step 4, the memory occupied by PTR is given back to the free pool.
char usn[20],name[10],branch[5];
unsigned long long int phno;
int sem;
struct Node *next;
};
typedef struct Node * NODE;
NODE temp,front = NULL,rear = NULL;
void insert();
void delete();
void display();
void main()
{
int choice, value;
switch(choice){
case 1:insert();
break;
case 2: delete();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong selection!!! Please try again!!!\n");
}
}
}
void insert()
{
NODE newNode;
newNode=(NODE)malloc(sizeof(struct Node));
printf("Enter USN: ");
scanf("%s",newNode->usn);
printf("Enter NAME: ");
scanf("%s",newNode->name);
printf("Enter Branch: ");
scanf("%s",newNode->branch);
printf("Enter phone Number: ");
scanf("%llu",&newNode->phno);
printf("Enter Semester: ");
scanf("%d",&newNode->sem);
newNode->next=NULL;
if(front == NULL)
{
else{
rear -> next = newNode;
rear = newNode;
rear->next=NULL;
}
printf("\nInsertion is Success!!!\n");
}
void delete()
{
if(front == NULL)
printf("\nQueue is Underflow!!!\n");
else{
temp = front;
front = front -> next;
printf("\nDeleted node is with usn: %s", temp->usn);
free(temp);
}
}
void display()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{
temp = front;
while(temp->next != NULL){
printf("The Student information in the node is\n");
printf("\nUSN:%s\nNAME:%s\nBRANCH:%s\nPHONE
NO.:%llu\nSEM:%d\n",temp->usn,temp->name,temp->branch,temp-
>phno,temp->sem);
}
printf("\nUSN:%s\nNAME:%s\nBRANCH:%s\nPHONE
NO.:%llu\nSEM:%d\n",temp->usn,temp->name,temp->branch,temp-
>phno,temp->sem);
}
}
Page 40
DATA STRUCTURES AND APPLICATIONS (BCS304)
Page 41
DATA STRUCTURES AND APPLICATIONS (BCS304)
Page 42
DATA STRUCTURES AND APPLICATIONS (BCS304)
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
struct node // polynomial node
{
int coef;
int x,y,z;
struct node *link;
};
typedef struct node *NODE;
Page 43
DATA STRUCTURES AND APPLICATIONS (BCS304)
x=(NODE)malloc(sizeof(struct node));
return x;
} // end of getnode
NODE readpoly()
{
NODE temp,head,cur;
char ch;
head=getnode(); // create a head node and set all values to -1 it is similar to FIRST in
SLL program
head->coef=-1;
head->x=-1;
head->y=-1;
head->z=-1;
head->link=head; // self reference
do
{
temp=getnode(); // create a polynomial node
printf("\nEnter the coefficient and exponent in decreasing order\n");
scanf("%d%d%d%d",&temp->coef,&temp->x,&temp->y,&temp->z );
cur=head;
while(cur->link!=head) // find the last node
cur=cur->link;
cur->link=temp; // connect new node to the last node
temp->link=head; // point back to head
printf("\nDo you want to enter more coefficients(y/n)");
fflush(stdin); // to clear the stdin buffer
scanf("%c",&ch);
} while(ch =='y' || ch == 'Y');
return head; // return the polynomial list
} // end of readpoly
Page 44
DATA STRUCTURES AND APPLICATIONS (BCS304)
void attach(int cf,int x1,int y1, int z1, NODE *ptr) // function to attach the A and B
polynomial node to C Polynomial
{
NODE temp;
temp=getnode();
temp->coef=cf;
temp->x=x1;
temp->y=y1;
temp->z=z1;
(*ptr)->link=temp;
*ptr=temp;
} // end of attach
Page 45
DATA STRUCTURES AND APPLICATIONS (BCS304)
b=b->link;
c=getnode(); // create list C to store A+B
c->coef=-1;
c->x=-1;
c->y=-1;
c->z=-1;
lastc=c;
do{
switch(compare(a,b))
{
case -1:attach(b->coef,b->x,b->y,b->z,&lastc);
b=b->link;
break;
case 0:if(starta==a) done=1;
else{
sum=a->coef+b->coef;
if(sum)
attach(sum,a->x, a->y,a->z,&lastc);
a=a->link;b=b->link;
}
break;
case 1: if(starta==a) done=1;
attach(a->coef,a->x, a->y,a->z,&lastc);
a=a->link;
break;
}
}while(!done); // repeate until not done
lastc->link=c; // point back to head of C
return c; // return answer
}
Page 46
DATA STRUCTURES AND APPLICATIONS (BCS304)
cur=ptr->link;
while(cur!=ptr) // To print from HEAD node till END node
{
printf("%d*x^%d*y^%d*z^%d",cur->coef,cur->x, cur->y, cur->z);
cur=cur->link; // move to next node
if (cur!=ptr)
printf(" + ");
}
} // end of print
void main(void)
Page 47
DATA STRUCTURES AND APPLICATIONS (BCS304)
{
int i, ch;
NODE a=NULL,b,c;
while(1)
{
printf("\n1: Represent first polynomial A");
printf("\n2: Represent Second polynomial B");
printf("\n3: Display the polynomial A");
printf("\n4: Display the polynomial B");
printf("\n5: Add A & B polynomials"); // C=A+B
printf("\n6: Evaluate polynomial C");
printf("\n7: Exit");
printf("\n Enter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nEnter the elements of the polynomial A");
a=readpoly();
break;
case 2:printf("\nEnter the elements of the polynomial B");
b= readpoly();
break;
case 3: print(a); // display polynomial A
break;
case 4:print(b); // display polynomial A
break;
case 5: c=addpoly(a,b); // C=A+B
printf("\nThe sum of two polynomials is: ");
print(c); // display polynomial C
printf("\n");
break;
case 6:evaluate(c); // Evaluate polynomial C
break;
case 7: return;
Page 48
DATA STRUCTURES AND APPLICATIONS (BCS304)
7. What is linked list? Explain the different types of linked list with examples.
8.Give a node structure to create a linked list of integers and write a C function to perform the
following.
a. Create a three-node list with data 10, 20 and 30
b. Inert a node with data value 15 in between the nodes having data values 10 and 20
c. Delete the node which is followed by a node whose data value is 20
d. Display the resulting singly linked list.
9. With node structure show how would you store the polynomials in linked lists? Write C
function for adding two polynomials represented as circular lists.
10. Write a C function to add two-polynomials represented as circular list with header node.
Page 49
DATA STRUCTURES AND APPLICATIONS (BCS304)
11. Write a C function to perform the following i. Reversing a singly linked list ii. Concatenating
singly linked list. iii. Finding the length of the circular linked list. iv. To search an element in
the singly linked list
12. Write a node structure of linked stack. Write a function to perform push and pop operations on
linked stack.
13.Write a function for singly linked lists with integer data, to search an element in the list that is
unsorted and a list that is sorted.
14. Write a node structure of linked queue. Write a function to perform enqueue and dequeue
operations on linked stack.
Page 50