0% found this document useful (0 votes)
7 views54 pages

DS Lab Manual

The document outlines experiments related to data structures, specifically focusing on implementing stacks and queues using arrays, as well as evaluating postfix expressions. It includes theoretical explanations, programming examples in C, and objectives for students to understand the concepts of stack (LIFO) and queue (FIFO) data structures. Additionally, it provides questions for further exploration and references for deeper learning.

Uploaded by

ahadshkk123
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)
7 views54 pages

DS Lab Manual

The document outlines experiments related to data structures, specifically focusing on implementing stacks and queues using arrays, as well as evaluating postfix expressions. It includes theoretical explanations, programming examples in C, and objectives for students to understand the concepts of stack (LIFO) and queue (FIFO) data structures. Additionally, it provides questions for further exploration and references for deeper learning.

Uploaded by

ahadshkk123
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/ 54

SAE, KONDHWA

Implement Graph using adjacency


9 Matrix with BFS & DFS
traversals.
10 Implement Dijkstra’s Algorithm.
Total Marks

Dept. of E & TC
(2023-24)
SAE, KONDHWA

EXPERIMENT 4
STACK AND QUEUE
Aim of Experiment: Implement Stack and Queue using arrays. Write a menu driven program
to perform following operations on stack a) Push b) Pop c) Display. Write a menu driven program
to perform following operations on Queue a) Insert b) Delete c) Display

OBJECTIVE: Objective of this experiment is to know concept of STACK and QUEUE. This assignment will
help the students to realize how the different operation on stack like push, pop, display can be implemented. This
assignment will help the student to realize the implementation difference between stack and queue. Also this will
clear the implementation concepts queue.

Stack Theory: Stack (data structure)

"Pushdown" redirects here..

Simple representation of a stack

In computer science, a stack is a last in, first out (LIFO) abstract data type and data structure. A stack can have
any abstract data type as an element, but is characterized by only two fundamental operations: push and pop. The
push operation adds to the top of the list, hiding any items already on the stack, or initializing the stack if it is
empty. The pop operation removes an item from the top of the list, and returns this value to the caller. A pop
either reveals previously concealed items, or results in an empty list.

A stack is a restricted data structure, because only a small number of operations are performed on it. The nature
of the pop and push operations also mean that stack elements have a natural order. Elements are removed from
the stack in the reverse order to the order of their addition: therefore, the lower elements are typically those that
have been in the list the longest.

Stack Implementation

In most high level languages, a stack can be easily implemented either through an array or a linked list. What
identifies the data structure as a stack in either case is not the implementation but the interface: the user is only
allowed to pop or push items onto the array or linked list, with few other helper operations. The following will
demonstrate array implementation, using C.

Dept. of E & TC
(2023-24)
SAE, KONDHWA

The array implementation aims to create an array where the first element (usually at the zero-offset) is the bottom.
That is, array[0] is the first element pushed onto the stack and the last element popped off. The program must
keep track of the size, or the length of the stack. The stack itself can therefore be effectively implemented as a
two-element structure in C:

typedef struct {
int size;
int items[STACKSIZE];
} STACK;

The push() operation is used both to initialize the stack, and to store values to it. It is responsible for inserting
(copying) the value into the ps->items[] array and for incrementing the element counter (ps->size). In a
responsible C implementation, it is also necessary to check whether the array is already full to prevent an
overrun.

void push(STACK *ps, int x)


{
if (ps->size == STACKSIZE) {
fputs("Error: stack overflow\n", stderr);
abort();
} else
ps->items[ps->size++] = x;
}

The pop() operation is responsible for removing a value from the stack, and decrementing the value of ps-
>size. A responsible C implementation will also need to check that the array is not already empty.

int pop(STACK *ps)


{
if (ps->size == 0){
fputs("Error: stack underflow\n", stderr);
abort();
} else
return ps->items[--ps->size];
}

Queue Theory: A queue is a particular kind of collection in which the entities in the collection are kept in
order and the principal (or only) operations on the collection are the addition of entities to the rear terminal
position and removal of entities from the front terminal position. This makes the queue a First-In-First-Out (FIFO)
data structure. In a FIFO data structure, the first element added to the queue will be the first one to be removed.
This is equivalent to the requirement that whenever an element is added, all elements that were added before have
to be removed before the new element can be invoked. A queue is an example of a linear data structure.

Queues provide services in computer science, transport and operations research where various entities such as
data, objects, persons, or events are stored and held to be processed later. In these contexts, the queue performs
the function of a buffer.

Queues are common in computer programs, where they are implemented as data structures coupled with access
routines, as an abstract data structure or in object-oriented languages as classes. Common implementations are
circular buffers and linked lists.

Dept. of E & TC
(2023-24)
SAE, KONDHWA

Representing a Queue

The defining attribute of a queue data structure is the fact that allows access to only the front and back of the
structure. Furthermore, elements can only be removed from the front and can only be added to the back. In this
way, an appropriate metaphor often used to represent queues is the idea of a checkout line (Ford/Topp p. 385).
Other examples of queues are people traveling up an escalator, machine parts on an assembly line, or cars in line
at a petrol station. The recurring theme is clear: queues are essentially the same as a queue you would get in a
shop waiting to pay.

In each of the cases, the customer or object at the front of the line was the first one to enter, while at the end of
the line is the last to have entered. Every time a customer finishes paying for their items (or a person steps off the
escalator, or the machine part is removed from the assembly line, etc.) that object leaves the queue from the front.
This represents the queue “dequeue” function. Every time another object or customer enters the line to wait, they
join the end of the line and represent the “enqueue” function. The queue “size” function would return the length
of the line, and the “empty” function would return true only if there was nothing in the line.

Queue implementation
Theoretically, one characteristic of a queue is that it does not have a specific capacity. Regardless of how many
elements are already contained, a new element can always be added. It can also be empty, at which point
removing an element will be impossible until a new element has been added again.

A practical implementation of a queue, e.g. with pointers, of course does have some capacity limit, that depends
on the concrete situation it is used in. For a data structure the executing computer will eventually run out of
memory, thus limiting the queue size. Queue overflow results from trying to add an element onto a full queue
and queue underflow happens when trying to remove an element from an empty queue.

A bounded queue is a queue limited to a fixed number of items.

CONCLUSION:

Dept. of E & TC
(2023-24)
SAE, KONDHWA

NOTE: PROGRAM & OUTPUT SHOULD BE ATTATCHED

QUESTIONS STACK:
1) what is a data structure? Explain types of data structures with example?
2) Write Applications of Stack?
3) How to Convert Postfix Expression To Infix Using Stack?
4) What is a stack? Which type of data structure is stack?

QUESTIONS QUEUE:
1) Differentiate between linear queue &circular queue?
2) Give applications of queue?
3) What is a queue? Explain with example?
4) Write the empty and full conditions of queue using arrays?

References :

1. “C programming “ Balguruswamy.
2. ‘Fundamentals of datastructures” sartaj sahani.
3. “Data structures “ Tananbom

Dept. of E & TC
(2023-24)
SAE, KONDHWA

Program:

//Stack Using Array

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define size 5
typedef struct stack
{
int top;
int data[size];
}s;
void push(s*,int);
int pop(s*);
void display(s*);
void main(void)
{
s st;
int choice,item,item_deleted;
clrscr();
st.top=-1;
while(1)
{
printf("\nEnter the choice");
printf("\n1.push\n2.pop\n3.display\n4.exit");
printf("\nchoice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\n Enter the item");
scanf("%d",&item);
push(&st,item);
break;
case 2:
item_deleted=pop(&st);
if(item_deleted!=-1)
{
printf("\n Item_deleted=%d",item_deleted);
}
break;
case 3:
display(&st);
break;
default:
exit(0);
}
}
}
void push(s *st,int item)
{
if(st->top==size-1)
{
Dept. of E & TC
(2023-24)
SAE, KONDHWA

printf("\nstack is over flow");


}
else
{
st->top++;
st->data[st->top]=item;
}
display(st);
}
int pop(s *st)
{
int item_deleted;
if(st->top==-1)
{
printf("\nstack is underflow");
return -1;
}
item_deleted=st->data[st->top--];
display(st);
return item_deleted;
}
void display(s *st)
{
int i;
if(st->top==-1)
{
printf("\nstack is empty");
}
else
{
printf("\n contents of stack are:");
for(i=st->top;i>-1;i--)
{
printf("\n%d",st->data[i]);
}
}
}

/* OUTPUT */

2.pop
3.display
4.exit
choice:1

Enter the item20

contents of stack are:


20
10
Enter the choice
1.push
2.pop
Dept. of E & TC
(2023-24)
SAE, KONDHWA

3.display
4.exit
choice:1

Enter the item30

contents of stack are:


30
20
10
Enter the choice
1.push
2.pop
3.display
4.exit
choice:2

contents of stack are:


20
10
Item_deleted=30
Enter the choice
1.push
2.pop
3.display
4.exit
choice:3

contents of stack are:


20
10
Enter the choice
1.push
2.pop
3.display
4.exit
choice:

Dept. of E & TC
(2023-24)
SAE, KONDHWA

//Queue using array


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define queue_size 5

int q[10];
int r;
int f;

void insert_rare(int item);


int delete_front();
void display();

int main()
{
int item,item_deleted,choice;
r=-1;
f=0;

//clrscr();
while(1)
{
printf("\n\nenter your choice");
printf("\n1)insert\n2)Delete\n3)display\n4)quit\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nenter the item");
scanf("%d",&item);
insert_rare(item);
break;
case 2:
item_deleted=delete_front();
if(item_deleted!=-1)
printf("\nitem deleted=%d",item_deleted);
break;
case 3:
display();
break;
default:
exit(0);
}
}
}
void insert_rare(int item)
{
if(r==queue_size-1)
{
printf("\nqueue is overflowed");
return -1:
}
Dept. of E & TC
(2023-24)
SAE, KONDHWA

r++;
q[r]=item;
}
int delete_front()
{
int item_deleted;
if(f>r)
{
printf("\nqueue is underflowed");
return -1;
}
item_deleted=q[f];
f++;
if(f>r)
{
f=0;
r=-1;
}
return item_deleted;
}

void display()
{
int i;
if(f>r)
{
printf("\nqueue is empty");
return;
}
printf("\ncontnets of queue are:");
for(i=f;i<=r;i++)
{
printf("%d",q[1]);
}
}

OUTPUT

enter your choice


1)insert
2)Delete
3)display
4)quit
1

enter the item5

enter your choice


1)insert
2)Delete
3)display
4)quit
1
Dept. of E & TC
(2023-24)
SAE, KONDHWA

enter the item4

enter your choice


3

contnets of queue are:5 4 3

enter your choice


1)insert
2)Delete
3)display
4)quit
2

item deleted=5

enter your choice


1)insert
2)Delete
3)display
4)quit
3

contnets of queue are:4 3

enter your choice


1)insert
2)Delete
3)display
4)quit

1)insert
2)Delete
3)display
4)quit
1

enter the item3

enter your choice


1)insert
2)Delete
3)display
4)quit

Dept. of E & TC
(2023-24)
SAE, KONDHWA

EXPERIMENT 5
Evaluate postfix expression (input will be postfix expression).

Title: Evaluation of postfix expression

Aim of Experiment:

Take postfix expression as a input and evaluate it for result.

Objective :

This assignment will help the student to know how the postfix expression evaluation.

Theory:

The expression a + b*(c - d )+ e written in postfix form is abcd - * + e +. This looks rather cryptic. You can get
the idea most easily if you read it backwards as `` add e to (add (times (c - d) and b) to a)''. A few more examples
are shown in Table which may serve better than an elaborate explanation:

Table: Converting expressions to postfix notation.


a+(b+c) abc++
(a+b)+c ab+c+
a-b*c abc*-
(a/b)*(c/d) ab/cd/*
a/(b+c*d-e) abcd*+e-/
a-b*c+d/e abc*-de/+

Algorithm:

Postfix Expression :

STEP 1: Read the given postfix expression into a string called postfix.
STEP 2: Read one character at a time & perform the following operations :
1. If the read character is an operand, then convert it to float and push it onto
the stack.

Dept. of E & TC
(2023-24)
SAE, KONDHWA

2. If the character is not an operand, then pop the operator from stack And assign to
OP2. Similarly, pop one more operator from stack and assign to OP1.
3. Evaluate the result based on operator x.
4. Push the result (based on operator x) onto the stack.
STEP 3: Repeat STEP 2 till all characters are processed from the input string.
STEP 4: Return the result from this procedure or algorithm and display the
result in main program.

In normal algebra we use the infix notation like a+b*c. The corresponding postfix notation is abc*+. The
algorithm for the evaluation of postfix ex. is as follows :

 Scan the Postfix string from left to right.


 Initialize an empty stack.
 If the scanned character is an operand, add it to the stack. If the scanned character is an operator, there
will be at least two operands in the stack.
o If the scanned character is an Operator, then we store the top most element of the stack(topStack)
in a variable temp. Pop the stack. Now evaluate topStack(Operator)temp. Let the result of this
operation be retVal. Pop the stack and Push retVal into the stack.
o Repeat this step till all the characters are scanned.
 After all characters are scanned, we will have only one element in the stack. Return topStack.

Input:

Input is the postfix expression which we want to evaluate.

Output:

Output is the result of postfix expression .

FAQs :

1. How it is useful in different application.


2. What are the different ways to implement it.
3. What are the limitations of it.

References :

4. “C programming “ Balguruswamy.
5. ‘Fundamentals of datastructures” sartaj sahani.
6. “Data structures “ Tananbom

Conclusion:

Dept. of E & TC
(2023-24)
SAE, KONDHWA

Program:
/*** Program for evaluation of Postfix Expression ***/
#include<stdio.h>
#include<conio.h>
#include<ctype.h> /* for isdigit()function */
#include<math.h> /* for pow() function */
#define max 100
struct post
{
int stack[max];
int top;

}pf;
int evaluate(char *s);
void push(struct post *q,int val);
int pop(struct post *q);
void main()
{
int n1,n2,n3;
char expr[max];
int val,res;
clrscr();
printf("\n\nenter postfix expr\t");
gets(expr);
val=evaluate(expr);
printf("\nthe evaluation is \t%d",val);
getch();

}
int evaluate(char *s)
{
int res,val,n1,n2,n3;
struct post pf;
pf.top=-1;
while(*s!='\0')
{
if(isdigit(*s))
{
res=*s-'0'; /* '0'=ASCII 48, '9'=ASCII 57 */
push(&pf,res);
}
else
{
n1=pop(&pf);
n2=pop(&pf);
switch(*s)
{
case'+':n3=n2+n1;
break;
case'-':n3=n2-n1;
break;
case'*':n3=n2*n1 ;
break;
Dept. of E & TC
(2023-24)
SAE, KONDHWA

case'/':n3=n2/n1;
break;
case'$':n3=pow(n2,n1) ;
break;
}
push(&pf,n3);
}
s++;
}
res=pop(&pf);
return(res);
}

//pushing the data on stack

void push(struct post *q,int val)


{
if(q->top==max-1)
{
printf("stack full");
return;
}
q->top++;
q->stack[q->top]=val;
}
//poping the data

int pop(struct post *q)


{
int val;
if(q->top==-1)
{
printf("stack empty");
//return;
}

val=q->stack[q->top];
q->top--;
return(val);
}

Dept. of E & TC
(2023-24)
SAE, KONDHWA

EXPERIMENT 6
SINGLY LINKED LIST
Aim of Experiment:

Create a singly linked list with options:

a. Insert (at front, at end, in the middle), b. Delete (at front, at end, in the middle),

c. Display, d. Display Reverse, e. Revert the SLL.


OBJECTIVE:

After performing this experiment, student should be able to:

 Understand the concept of a singly linked list and various operations on it

 Write functions for other simple operations on such a linked list.

 Design a program for other variants of singly linked list that include use of a pointer to last node, header
node, circular linked list, and circular list with header node.

Theory: Singly-Linked Lists


The singly-linked list is the most basic of all the linked data structures. A singly-linked list is simply a sequence
of dynamically allocated objects, each of which refers to its successor in the list. Despite this obvious simplicity,
there are myriad implementation variations. Figure shows several of the most common singly-linked list
variants.

Figure: Singly-linked list variations.


Dept. of E & TC
(2023-24)
SAE, KONDHWA

The basic singly-linked list is shown in Figure (a). Each element of the list refers to its successor and the last
element contains the null reference. One variable, labeled head in Figure (a), is used to keep track of the list.

The basic singly-linked list is inefficient in those cases when we wish to add elements to both ends of the list.
While it is easy to add elements at the head of the list, to add elements at the other end (the tail ) we need to locate
the last element. If the basic basic singly-linked list is used, the entire list needs to be traversed in order to find its
tail.

Figure (b) shows a way in which to make adding elements to the tail of a list more efficient. The solution uses
a second variable, tail , which refers to the last element of the list. Of course, this time efficiency comes at the
cost of the additional space used to store the variable tail.

The singly-linked list labeled (c) in Figure illustrates two common programming tricks. There is an extra
element at the head of the list called a sentinel . This element is never used to hold data and it is always present.
The principal advantage of using a sentinel is that it simplifies the programming of certain operations. For
example, since there is always a sentinel standing guard, we never need to modify the head variable. Of course,
the disadvantage of a sentinel such as that shown in (c) is that extra space is required, and the sentinel needs to be
created when the list is initialized.

The list (c) is also a circular list . Instead of using a null reference to demarcate the end of the list, the last
element of the list refers to the sentinel. The advantage of this programming trick is that insertion at the head of
the list, insertion at the tail of the list, and insertion at an arbitrary position of the list are all identical operations.

Of course, it is also possible to make a circular, singly-linked list that does not use a sentinel. Figure (d) shows
a variation in which a single variable is used to keep track of the list, but this time the variable, tail, refers to the
last element of the list. Since the list is circular in this case, the first element follows the last element of the list.
Therefore, it is relatively simple to insert both at the head and at the tail of this list. This variation minimizes the
storage required, at the expense of a little extra time for certain operations.

Figure illustrates how the empty list (i.e., the list containing no list elements) is represented for each of the
variations given in Figure . Notice that the sentinel is always present in list variant (c). On the other hand, in
the list variants which do not use a sentinel, the null reference is used to indicate the empty list.

Figure: Empty singly-linked lists.

Dept. of E & TC
(2023-24)
SAE, KONDHWA

In the following sections, we will present the implementation details of a generic singly-linked list. We have
chosen to present variation (b)--the one which uses a head and a tail--since is supports append and prepend
operations efficiently.

Algorithm:

Insertion in ordered list:

// x is the data element of the node to be inserted in linked list

// list is the starting node of the linked list

// next refers to the next node of the linked list

// info refers to info field of the node

Getnode (new)

Info (new) =x

next (new) =null

if list = null

list = new

else

begin

p=list

if x < info (p)

then next (new) = list

list = new

else

begin

while (next (p) <> null) and (x >= info (next (p))) do

p= next (p)

next (new)= next(p)

next (p) = new

end else //end of inner else


Dept. of E & TC
(2023-24)
SAE, KONDHWA

end else //end of outer else

Deleting from a linked list:

// current initially refers to first node of the linked list

// trail refers to one node previous to current

current = list

trail = null

while ( current <> null) and (info (current) <> x) do

begin

trail = current

current = next (current)

end/* end of the loop to search the node */

if current not null

then if trail = null

then

list = next (list) /* delete the first node */

else

next (trail) = next (current)

freenode (current)

else print (“node with the given value doesn’t exist in the list” )

Search a node in a given linked list:

// current initially refers to the first node of the linked list

// next refers to the next node

count=0

while (current <> null) and info (current) <> x) do

current = next (current)

count = count +1

Dept. of E & TC
(2023-24)
SAE, KONDHWA

end // end of the loop

if (current = null)

call print(“ node with the given value doesn’t exist in the list”)

else

display the position and the content of the node

Display the content of linked list:

// list is the starting node of the linked list

if (list = null)

call print(“ linked list is empty “)

else

while (current <> null ) do

call print( info(current))

current = next (current)

end //end of loop

end //end else

NOTE: PROGRAM & OUTPUT SHOULD BE ATTATCHED

CONCLUSION: Thus we have learnt how to create singly linked list and we implemented singly linked list .

QUESTIONS: 1) What is a SLL? Explain with example?


2) What are the different types of Linked List? Explain with example?
3) Write a C function to reverse/inverse a Singly-Linked List.
4) What is dynamic memory allocation? Write the syntax for the function used?

References:
 “C programming “ Balguruswamy.
 ‘Fundamentals of datastructures” sartaj sahani.
 “Data structures “ Tananbom

Dept. of E & TC
(2023-24)
SAE, KONDHWA

Program:
//Singly Linked List

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
# include<malloc.h>
typedef struct Node
{
int data;
struct Node *next;
}*node;
node getnode();
node create(node first);
node insert_front(int item,node first) ;
node delete_front(node first);
node insert_rear(int item ,node first) ;
node delete_rear(node first);
void search(node first);
void display(node first);
int main()
{
int item, choice;
node first =NULL;
//clrscr();
while(1)
{
printf("\n\n1:create\n2:insert a node from front\n3:insert from rear
end\n4:delete from front\n5:delete from rear end\n6:search\n7:display\n8:exit");
printf("\n enter the choice") ;
scanf("%d",&choice);
switch(choice)
{
case 1 :
first=create(first);
break;
case 2 :
printf("\nenter the item to be inserted") ;
scanf("%d",&item);
first=insert_front(item ,first);
break;
case 3:
printf("\nenter the item to be inserted") ;
scanf("%d",&item);
first=insert_rear(item ,first);
break;
case 4:
first=delete_front(first) ;
break;
case 5:
first=delete_rear(first) ;
break;
Dept. of E & TC
(2023-24)
SAE, KONDHWA

case 6:
search(first) ;
break;
case 7:
display(first);
break;
default:
exit(0);
}
}
//getch();
return 0;
}
node getnode()
{
node temp;
temp=(node)malloc(1*sizeof(struct Node));
if(temp==NULL)
{
printf("\n out of memory");
}
return temp;
}
node create(node first)
{
node temp,current;
int i,n,item;
printf("\n enter the nos of nodes");
scanf("%d",&n);
for(i=0;i<n;i++)
{
temp=getnode();
temp->next=NULL;
printf("\nenter the item");
scanf("%d",&item);
temp->data=item;
if(i==0)
{
first=temp;
current=first;
}
else
{
temp->next=current;
current=temp;
}
}
return current;
}
node insert_front(int item,node first)
{
node temp;
temp=getnode();
temp->next=NULL;
Dept. of E & TC
(2023-24)
SAE, KONDHWA

temp->data=item;
if(first==NULL)
{
first=temp;
}
else
{
temp->next=first;
first=temp;
}
return first;
}
node insert_rear(int item, node first) \
{
node temp,current;
temp=getnode();
temp->next=NULL;
temp->data=item;
if(first==NULL)
{
first=temp;
}
else
{
current=first;
while(current->next!=NULL)
{
current=current->next;
}
current->next=temp;
}
return first;
}
node delete_front(node first)
{
node temp;
int item_deleted;
if(first==NULL)
{
printf("\n first is empty");
return first;
}
else
{
temp=first;
first=first->next;
item_deleted=temp->data;
printf("\n iteam deleted is%d",item_deleted);
temp->next=NULL;
free(temp);
temp=NULL;
return first;
}
}
Dept. of E & TC
(2023-24)
SAE, KONDHWA

void search(node first)


{
node current;
int item,pos=0,flag=0;
printf("enter the item to be searched") ;
scanf("%d",&item);
current=first;
while(current!=NULL)
{
if(item==current->data)
{
printf("\n item located at %dth position",pos+1);
flag=1;
}
pos++;
current=current->next;
}
if(flag==0)
printf("\n item not found");
}
void display(node first)
{
node current;
if(first==NULL)
{
printf("\n list is empty") ;
}
else
{
printf("element in list are:");
current=first;
while(current!=NULL)
{
printf("\t%d",current->data);
current=current->next;
}
}
}
node delete_rear(node first)
{
node previous,current;
int item_deleted;
if(first==NULL)
{
printf("\n list is empty");
}
else
{
current=first;
while(current->next!=NULL)
previous=current;
current=current->next;
previous->next=NULL;
item_deleted=current->data;
Dept. of E & TC
(2023-24)
SAE, KONDHWA

printf("\n item deleted=%d",item_deleted);


free(current);
}
return first;
}

//================================\\
Output

1:create
2:insert a node from front
3:insert from rear end
4:delete from front
5:delete from rear end
6:search
7:display
8:exit
enter the choice1

enter the nos of nodes3

enter the item10

enter the item20

enter the item30

1:create
2:insert a node from front
3:insert from rear end
4:delete from front
5:delete from rear end
6:search
7:display
8:exit
enter the choice7
element in list are: 30 20 10

1:create
2:insert a node from front
3:insert from rear end
4:delete from front
5:delete from rear end
6:search
7:display
8:exit
enter the choice2

enter the item to be inserted25

1:create
Dept. of E & TC
(2023-24)
SAE, KONDHWA

2:insert a node from front


3:insert from rear end
4:delete from front
5:delete from rear end
6:search
7:display
8:exit
enter the choice7
element in list are: 25 30 20 10
enter the choice3

enter the item to be inserted35

1:create
2:insert a node from front
3:insert from rear end
4:delete from front
5:delete from rear end
6:search
7:display
8:exit
enter the choice7
element in list are: 25 30 20 10 35
enter the choice4

iteam deleted is25

Dept. of E & TC
(2023-24)
SAE, KONDHWA

EXPERIMENT 7
STACK AND QUEUE
Aim of Experiment: Implement Stack and Queue using linked list. Write a menu driven program
to perform following operations on stack a) Push b) Pop c) Display. Write a menu driven program to
perform following operations on Queue a) Insert b) Delete c) Display

OBJECTIVE: Objective of this experiment is to know concept of STACK and QUEUE. This assignment will
help the students to realize how the different operation on stack like push, pop, display can be implemented. This
assignment will help the student to realize the implementation difference between stack and queue. Also this will
clear the implementation concepts queue.

Stack Theory: Stack (data structure)

"Pushdown" redirects here..

Simple representation of a stack

In computer science, a stack is a last in, first out (LIFO) abstract data type and data structure. A stack can have
any abstract data type as an element, but is characterized by only two fundamental operations: push and pop. The
push operation adds to the top of the list, hiding any items already on the stack, or initializing the stack if it is
empty. The pop operation removes an item from the top of the list, and returns this value to the caller. A pop
either reveals previously concealed items, or results in an empty list.

A stack is a restricted data structure, because only a small number of operations are performed on it. The nature
of the pop and push operations also mean that stack elements have a natural order. Elements are removed from
the stack in the reverse order to the order of their addition: therefore, the lower elements are typically those that
have been in the list the longest.

Stack Implementation

In most high level languages, a stack can be easily implemented either through an array or a linked list. What
identifies the data structure as a stack in either case is not the implementation but the interface: the user is only
allowed to pop or push items onto the array or linked list, with few other helper operations. The following will
demonstrate linked list implementation, using C.

Dept. of E & TC
(2023-24)
SAE, KONDHWA

The linked-list implementation is equally simple and straightforward. In fact, a stack linked-list is much simpler
than most linked-list implementations: it requires that we implement a linked-list where only the head node or
element can be removed, or popped, and a node can only be inserted by becoming the new head node.

Unlike the array implementation, our structure typedef corresponds not to the entire stack structure, but to a single
node:

typedef struct stack {


int data;
struct stack *next;
} STACK;

Such a node is identical to a typical linked-list node, at least to those that are implemented in C.

The push() operation both initializes an empty stack, and adds a new node to a non-empty one. It works by
receiving a data value to push onto the stack, along with a target stack, creating a new node by allocating memory
for it, and then inserting it into a linked list as the new head:

void push(STACK **head, int value)


{
STACK *node = malloc(sizeof(STACK)); /* create a new node */

if (node == NULL){
fputs("Error: no space available for node\n", stderr);
abort();
} else { /* initialize node */
node->data = value;
node->next = empty(*head) ? NULL : *head; /* insert new head if any */
*head = node;
}
}

A pop() operation removes the head from the linked list, and assigns the pointer to the head to the previous
second node. It check whether the list is empty before popping from it:

int pop(STACK **head)


{
if (empty(*head)) { /* stack is empty */
fputs("Error: stack underflow\n", stderr);
abort();
} else { /* pop a node */
STACK *top = *head;
int value = top->data;
*head = top->next;
free(top);
return value;
}

Queue Theory: A queue is a particular kind of collection in which the entities in the collection are kept in
order and the principal (or only) operations on the collection are the addition of entities to the rear terminal
position and removal of entities from the front terminal position. This makes the queue a First-In-First-Out (FIFO)
data structure. In a FIFO data structure, the first element added to the queue will be the first one to be removed.

Dept. of E & TC
(2023-24)
SAE, KONDHWA

This is equivalent to the requirement that whenever an element is added, all elements that were added before have
to be removed before the new element can be invoked. A queue is an example of a linear data structure.

Queues provide services in computer science, transport and operations research where various entities such as
data, objects, persons, or events are stored and held to be processed later. In these contexts, the queue performs
the function of a buffer.

Queues are common in computer programs, where they are implemented as data structures coupled with access
routines, as an abstract data structure or in object-oriented languages as classes. Common implementations are
circular buffers and linked lists.

Representing a Queue

The defining attribute of a queue data structure is the fact that allows access to only the front and back of the
structure. Furthermore, elements can only be removed from the front and can only be added to the back. In this
way, an appropriate metaphor often used to represent queues is the idea of a checkout line (Ford/Topp p. 385).
Other examples of queues are people traveling up an escalator, machine parts on an assembly line, or cars in line
at a petrol station. The recurring theme is clear: queues are essentially the same as a queue you would get in a
shop waiting to pay.

In each of the cases, the customer or object at the front of the line was the first one to enter, while at the end of
the line is the last to have entered. Every time a customer finishes paying for their items (or a person steps off the
escalator, or the machine part is removed from the assembly line, etc.) that object leaves the queue from the front.
This represents the queue “dequeue” function. Every time another object or customer enters the line to wait, they
join the end of the line and represent the “enqueue” function. The queue “size” function would return the length
of the line, and the “empty” function would return true only if there was nothing in the line.

Queue implementation
Theoretically, one characteristic of a queue is that it does not have a specific capacity. Regardless of how many
elements are already contained, a new element can always be added. It can also be empty, at which point
removing an element will be impossible until a new element has been added again.

Dept. of E & TC
(2023-24)
SAE, KONDHWA

A practical implementation of a queue, e.g. with pointers, of course does have some capacity limit, that depends
on the concrete situation it is used in. For a data structure the executing computer will eventually run out of
memory, thus limiting the queue size. Queue overflow results from trying to add an element onto a full queue
and queue underflow happens when trying to remove an element from an empty queue.

A bounded queue is a queue limited to a fixed number of items.

CONCLUSION:

NOTE: PROGRAM & OUTPUT SHOULD BE ATTATCHED

QUESTIONS STACK:
1) what is a data structure? Explain types of data structures with example?
2) Write Applications of Stack?
3) How to Convert Postfix Expression To Infix Using Stack?
4) What is a stack? Which type of data structure is stack?

QUESTIONS QUEUE:
1) Differentiate between linear queue &circular queue?
2) Give applications of queue?
3) What is a queue? Explain with example?
4) Write the empty and full conditions of queue using arrays?

References :

1. “C programming “ Balguruswamy.
2. ‘Fundamentals of datastructures” sartaj sahani.
3. “Data structures “ Tananbom

Dept. of E & TC
(2023-24)
SAE, KONDHWA

Program:

//Stack using Singly Linked List

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}*NODE;
NODE getnode(void);
NODE push(int,NODE);
NODE pop(NODE head);
NODE create(NODE first);
void display(NODE head);
int main()
{
int ch,item,x;
NODE temp,head=NULL;
//clrscr();
while(1)
{
printf("\n Enter the choice");
printf("\n 1:push\n2:pop\n3:display\n4:exit");
printf("\n choice =");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n enter to be pushed\n");
scanf("%d",&item);
head=push(item,head);
break;
case 2:
head=pop(head);
break;
case 3:
display(head);
break;
default:exit(0);
}
}
return 0;
}
NODE push(int item,NODE head)
{
NODE temp;
temp=getnode();
temp->data=item;
temp->next=NULL;
if(head==NULL)
Dept. of E & TC
(2023-24)
SAE, KONDHWA

head=temp;
else
{
temp->next=head;
head=temp;
}
display(head);
return head;
}
NODE pop(NODE head)
{
NODE temp;
int x;
if (head==NULL)
{
printf("\n stack is empty");
}
else
{
temp=head;
printf("element popped is: %d",temp->data);
head=head->next;
temp->next=NULL;
free(temp);
display(head);
}
return head;
}
void display(NODE head)
{
NODE temp;
if(head==NULL)
{
printf("\n stack is empty");
}
else
{
temp=head;
printf("\n the elements in stack are:");
while(temp!=NULL)
{
printf("\n %d",temp->data);
temp=temp->next;
}
}
}
NODE getnode()
{
NODE temp;
temp=(NODE)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("\n memory not available");
exit(0);
Dept. of E & TC
(2023-24)
SAE, KONDHWA

}
return temp;
}
NODE create(NODE first)
{
NODE temp;
int i,n,item;
printf("\n please enter the no of nodes");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n please enter the data");
scanf("%d",&item);
temp=getnode();
temp->data=item;
temp->next=NULL;
if(first==NULL)
{
first=temp;
}
else
{
temp->next=first;
first=temp;
}
}return first;
}

/* OUTPUT */

Enter the choice


1:push
2:pop
3:display
4:exit
choice =1

enter to be pushed
10

the elements in stack are:


10
Enter the choice
1:push
2:pop
3:display
4:exit
choice =1

enter to be pushed
Dept. of E & TC
(2023-24)
SAE, KONDHWA

20

the elements in stack are:


20
10
Enter the choice
1:push
2:pop
3:display
4:exit
choice =1

enter to be pushed
20

the elements in stack are:


20
20
10
Enter the choice
1:push
2:pop
3:display
4:exit
choice =2
element popped is: 20
the elements in stack are:
20
10
Enter the choice
1:push
2:pop
3:display
4:exit
choice =2
element popped is: 20
the elements in stack are:
10
Enter the choice
1:push
2:pop
3:display
4:exit
choice =2
element popped is: 10
stack is empty
Enter the choice
1:push
2:pop
3:display
4:exit
choice =

Dept. of E & TC
(2023-24)
SAE, KONDHWA

/* ==================================================================
*Program Description : Program to implement Queue using Linked List
*Name :
*Class : SE(EnTC)
*Roll no :
*Date :
==================================================================*/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

//structure declaration
typedef struct node
{
int data;
struct node *next;
} *QUEUE;

//function declaration
QUEUE getnode(void);
QUEUE insert_rare(int item,QUEUE first);
QUEUE delete_front(QUEUE first);
void display(QUEUE first);

//======================main function==================

int main()
{
int ch,item;
QUEUE temp,first=NULL;
//clrscr();
while(1)
{
printf("\n\n Enter the choice");
printf("\n1):Insert\n2):Delete\n3):Display\n4):Exit\n");
scanf("%d",&ch);

switch(ch)
{
//enter choice from the user

case 1: printf("\n Item to b inserted\n");


scanf("%d",&item);
first=insert_rare(item,first);
break;
case 2: first=delete_front(first);
break;
case 3: display(first);
break;
default: exit(0);

}/*end of switch*/

}/*end of do_while*/
Dept. of E & TC
(2023-24)
SAE, KONDHWA

return 0;

}/*end of main*/

//function to insert a node into the queue


QUEUE insert_rare(int item,QUEUE first)
{
QUEUE temp,cur;
temp=getnode();
temp->data=item;
temp->next=NULL;
if(first==NULL)
return temp;
else
{
cur=first;
while(cur->next!=NULL)
{
cur=cur->next;
}
cur->next=temp;
}
return first;
}

//function to delete a node


QUEUE delete_front(QUEUE first)
{
QUEUE temp;
if(first==NULL)
{
printf("\n Queue is empty");
}
else
{
if(first->next==NULL)
{
printf("\n Item Deleted = %d",first->data);
free(first);
first=NULL;
return first;
}
else
{
temp=first;
first=first->next;
temp->next=NULL;
printf("\n Item Deleted = %d",temp->data);
temp =NULL;
free(temp);
// return first;
}
}
return first;
Dept. of E & TC
(2023-24)
SAE, KONDHWA

//function to display the stack


void display(QUEUE first)
{
QUEUE temp;
if(first==NULL)
{
printf("\n Queue is empty");
}
else
{
printf("\n The contents of queue are : ");
temp=first;
while(temp!=NULL)
{
printf("\t%d",temp->data);
temp=temp->next;
}
}
}

// function to allocate memory for a node


QUEUE getnode()
{
QUEUE x;
x=(QUEUE)malloc(sizeof(QUEUE));
if(x==NULL)
{
printf("\n memory not available");

}
return x;
}
//=====================end of program===================

Dept. of E & TC
(2023-24)
SAE, KONDHWA

EXPERIMENT 8
TREES
Aim of Experiment: Binary search tree: Create, search, recursive traversals.
OBJECTIVE:

 To implement logic for constructing binary search tree.


 To implement following primitive operations-
 Create, search, recursive traversals

Theory: In computer science, a tree is a widely-used data structure that emulates a hierarchical tree structure
with a set of linked nodes. Mathematically, it is not a tree, but an arborescence an acyclic connected graph where
each node has zero or more children nodes and at most one parent node. Furthermore, the children of each node
have a specific order.

Terminology
A node is a structure which may contain a value, a condition, or represent a separate data structure (which could
be a tree of its own). Each node in a tree has zero or more child nodes, which are below it in the tree (by
convention, trees grow down, not up as they do in nature). A node that has a child is called the child's parent
node (or ancestor node, or superior). A node has at most one parent.

Nodes that do not have any children are called leaf nodes. They are also referred to as terminal nodes.

The height of a node is the length of the longest downward path to a leaf from that node. The height of the root
is the height of the tree. The depth of a node is the length of the path to its root (i.e., its root path). This is
commonly needed in the manipulation of the various self balancing trees, AVL Trees in particular.
Conventionally, the value -1 corresponds to a subtree with no nodes, whereas zero corresponds to a subtree with
one node.

The topmost node in a tree is called the root node. Being the topmost node, the root node will not have parents.
It is the node at which operations on the tree commonly begin (although some algorithms begin with the leaf
nodes and work up ending at the root). All other nodes can be reached from it by following edges or links. (In
Dept. of E & TC
(2023-24)
SAE, KONDHWA

the formal definition, each such path is also unique). In diagrams, it is typically drawn at the top. In some trees,
such as heaps, the root node has special properties. Every node in a tree can be seen as the root node of the subtree
rooted at that node.

An internal node or inner node is any node of a tree that has child nodes and is thus not a leaf node.

A subtree of a tree T is a tree consisting of a node in T and all of its descendants in T. (This is different from the
formal definition of subtree used in graph theory.[1]) The subtree corresponding to the root node is the entire tree;
the subtree corresponding to any other node is called a proper subtree (in analogy to the term proper subset).

Tree representations
There are many different ways to represent trees; common representations represent the nodes as records allocated
on the heap (not to be confused with the heap data structure) with pointers to their children, their parents, or both,
or as items in an array, with relationships between them determined by their positions in the array (e.g., binary
heap).

Binary Tree:
A binary tree is a finite set of nodes which is either empty or consists of root and two disjoint binary trees
called the left sub-tree and right sub-tree.

Binary search tree:

Binary search tree is binary tree which have all the values less than the root will lie in left sub tree & having
values greater than the root lie in right sub tree.

In computer science a binary search tree (BST) is a node based binary tree data structure which has the
following properties:

 The left sub-tree of a node contains only nodes with keys less than the node's key.

 The right sub-tree of a node contains only nodes with keys greater than the node's key.

 Both the left and right sub-trees must also be binary search trees

Traversal:

Traversal is a systematic way of retrieving information from tree in such a way that no node will be left
unvisited or no node will be visited twice or more.

There are different techniques of traversals:


Dept. of E & TC
(2023-24)
SAE, KONDHWA

1) Pre-order
2) Post-order
3) In-order
4) Depth first search
5) Breadth first

Each of these methods start processing from root of tree.

1) Pre-order: In this data on the root node will be printed first then we move on the left sub-tree and go on
printing the data till we reach to the leftmost node. Print the data at that node and then move to the right
sub-tree.

2) In-order : In this traversal first we go towards the leftmost node to print data on that node then traversing
left sub-tree then print root node then traverse right subtree.

3) Post-order: In post order traversal we follow the LRD principle i.e. move to the leftmost node check if
right sub-tree is there or not if not then print the leftmost node, if right sub tree is there move towards
rightmost node.

CONCLUSION:

QUESTIONS: 1) Define a binary search tree?


2) Classify binary tress?

3) Define the terms node, leaf degree ,depth of a tree?

4) Construct the BST with the following data

10 45 67 34 21 78 90 33 and write its traversals

References:

 “C programming “ Balguruswamy.
 ‘Fundamentals of datastructures” sartaj sahani.
 “Data structures “ Tananbom

Program:
Dept. of E & TC
(2023-24)
SAE, KONDHWA

/*==============================================================
* Program Description : Program for Tree
* Name :
* Class : SE(EnTC)
* Roll no :
* Date :
=============================================================*/

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

//structure declaration

typedef struct bst


{
int item;
struct bst *lchild, *rchild;
}*BST;

//======== global declarations and fuction defeintions=======

BST create(BST T);


BST insert(int data, BST T);
BST search(int key, BST T);
void preorder(BST T);
void inorder(BST T);
void postorder(BST T);

//========== main function=================

int main (void)


{
BST T=NULL,p;
int key,data;
int ch;
//clrscr();
while(1)
{
printf("\n1:Create\n2:Search\n3:Insert\n4:Preorder"\
"\n5:Inorder\n6:Postorder\n7:Exit");
printf("\n Please enter the choice");
scanf("%d",&ch);
switch(ch)
{
//taking choice from the user

case 1:
T=create(T);
break;
case 2:
printf("\n Please enter the key to be found");
scanf("%d",&key);
Dept. of E & TC
(2023-24)
SAE, KONDHWA

p=search(key,T);
if(p==NULL)
printf("\n Key not found");
else
printf("\n Key found");
break;
case 3:
printf("\n Please enter the data to"\
"be inserted");

scanf("%d",&data);
T=insert(data,T);
break;

case 4:
preorder(T);
break;
case 5:
inorder(T);
break;
case 6:
postorder(T);
break;
case 7:
exit(0);

} /*end of switch*/

}/*end of do_while*/
return 0;

} /*end of main*/

//function to create tree

BST create(BST T)
{
int data,n ,i;
printf("\n Please enter the number of nodes");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Please enter the data");
scanf("%d",&data);
T=insert(data,T);
}
return T;
}

// function to insert a node

BST insert(int data, BST T)


{
BST temp;
Dept. of E & TC
(2023-24)
SAE, KONDHWA

BST cur, prev;


temp=(BST)malloc(sizeof(struct bst));
temp->item=data;
temp->lchild=NULL;
temp->rchild=NULL;
if(T==NULL)
return temp;
cur=T;
while(cur!=NULL)
{
prev=cur;
if(data>cur->item)
{
cur=cur->rchild;

}
else
{
cur=cur->lchild;
}
}
if(data>prev->item)
{
prev->rchild=temp;
}
else
{
prev->lchild=temp;
}
return T;
}

//function to search a node

BST search(int key, BST T)


{
while(T!=NULL)
{
if(key==T->item)
{
return T;
}
if(key>T->item)
{
T=T->rchild;
}
else
{
T=T->lchild;
}
}
return NULL;
}

Dept. of E & TC
(2023-24)
SAE, KONDHWA

//function for preorder traversal

void preorder(BST T)
{
if(T!=NULL)
{
printf("%d\t",T->item);
preorder(T->lchild);
preorder(T->rchild);
}
}

void inorder(BST T)
{
if(T!=NULL)
{
inorder(T->lchild);
printf("%d\t",T->item);
inorder(T->rchild);
}
}

//function for postorder traversal

void postorder(BST T)
{
if(T!=NULL)
{
postorder(T->lchild);
postorder(T->rchild);
printf("%d\t",T->item);
}
}

//========================end of program====================

Dept. of E & TC
(2023-24)
SAE, KONDHWA

EXPERIMENT 9
Graphs
Aim of Experiment:

Graph using adjacency Matrix with BFS & DFS traversals.


Objective:
 To implement logic for constructing graph using adjacency matrix.
 To implement following primitive operations-

DFS traversal, BFS traversal and Adjacency Matrix display

Theory: Graph:
In computer science, a graph is an abstract data structure that is meant to implement the graph concept from
mathematics

A graph data structure consists mainly of a finite (and possibly mutable) set of ordered pairs, called edges or arcs,
of certain entities called nodes or vertices. As in mathematics, an edge (x, y) is said to point or go from x to y.
The nodes may be part of the graph structure, or may be external entities represented by integer indices or
references.

Formal Definition: A graph G can be defined as a pair (V, E), where V is a set of vertices, and E is a set of
edges between the vertices.

G= (V, E)

Adjacency matrix:
In mathematics and computer science, an adjacency matrix (or one-hop connectivity matrix) is a means of
representing which vertices of a graph are adjacent to which other vertices. Another matrix representation for a
graph is the incidence matrix Specifically, the adjacency matrix of a finite graph G on n vertices is the n × n
matrix where the non-diagonal entry aij is the number of edges from vertex i to vertex j, and the diagonal entry
aii, depending on the convention, is either once or twice the number of edges (loops) from vertex i to itself.
Undirected graphs often use the former convention of counting loops twice, whereas directed graphs typically use
the later convention. There exists a unique adjacency matrix for each graph (up to permuting rows and columns),
and it is not the adjacency matrix of any other graph. In the special case of a finite simple graph, the adjacency
matrix is a (0, 1)-matrix m with zeros on its diagonal. If the graph is undirected, the adjacency matrix is symmetric.

Operations:

Dept. of E & TC
(2023-24)
SAE, KONDHWA

1) Create a graph.

2) Insert new node in created graph.

3) Delete node from the graph.

4) Search a node (DFS/BFS).

Input:
1) Adjacency matrix.

2) Enter the starting vertex for DFS/BFS.

Output:

Output is found by DFS/BFS.

Application:
1. Network Analysis.
2. Artificial Intelligence
3. Compiler writing
4. Computer Graphics
5. Finding shortest route

Conclusion:

Questions:
1. Explain adjacency matrix and adjacency list. Construct adjacency matrix and adjacency list for the
following graph.

12
A
B 1
17 7
15
F 2 E

19
10
C D 6
14
2. Explain what are BFS and DFS?
Dept. of E & TC
(2023-24)
SAE, KONDHWA

3. Explain the terms vertex ,edge in degree and out degree.

References:

1. “C programming “ Balguruswamy.
2. ‘Fundamentals of datastructures” sartaj sahani.
3. “Data structures “ Tananbom “

Dept. of E & TC
(2023-24)
SAE, KONDHWA

Program:
//Graphs
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<process.h>
int a[20][20],visited[20],rear=-1,front=0,queue[20];
void bfs(int,int);
void dfs(int,int);
void add(int);
int delet();
int outdegree(int vertex,int n)
{
int i,count=0;
for(i=0;i<n;i++)
{
if(a[vertex][i]==1)
count++;
}
return count;
}
int indegree(int vertex,int n)
{
int i,count=0;
for(i=0;i<n;i++)
{
if(a[i][vertex]==1)
count++;
}
return count;
}
int main()
{
int vertex,n,choice,i,j;
clrscr();
printf("enter the no of vertices=");
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("press 1 if %d has a node with %d else press 0=",i,j);
scanf("%d",&a[i][j]);
}
}
printf("the adjacency matrix is\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
printf("enter 1-bfs\
\n 2-dfs\
\n 3-indegree\
\n 4-outdegree\
\n 5-exit\n");
while(1)
{
Dept. of E & TC
(2023-24)
SAE, KONDHWA

printf("\nenter vertex=");
scanf("%d",&vertex);
printf("enter your choice=");
scanf("%d",&choice);
for(i=0;i<20;i++)
{ queue[i]=NULL;visited[i]=NULL;front=0;rear=-1; }
switch(choice)
{
case 1:
bfs(vertex,n);break;
case 2:
dfs(vertex,n);break;
case 3:
printf("indegree of %d vertex is %d\n",vertex,indegree(vertex,n));
break;
case 4:
printf("outdegree of %d vertex is %d\n",vertex,outdegree(vertex,n));
break;
case 5:
printf("your programme ends here!!!\n");
getch();
exit(0);
}
}
return 0;
}
void bfs(int vertex,int n)
{
int i;
visited[vertex]=1;
printf("%d\t",vertex);
for(i=0;i<n;i++)
{
if((a[vertex][i]!=0)&&(visited[i]==0))
{
add(i);
visited[i]=1;
}
}
vertex=delet();
if(vertex!=-9)
bfs( vertex, n);
}
void add(int no)
{
if(rear==19)
printf("quque is full!!!\n");
else
{
rear++;
queue[rear]=no;
}
}
int delet()
{
int k;
if(front>rear)
return(-9);
else
{
k=queue[front];
front++;
Dept. of E & TC
(2023-24)
SAE, KONDHWA

return(k);
}
}
void dfs(int vertex,int n)
{
int i;
visited[vertex]=1;
printf("%d\t",vertex);
for(i=0;i<n;i++)
{
if((a[vertex][i]==1)&&(visited[i]==0))
dfs(i,n) ;
}
}

Dept. of E & TC
(2023-24)
SAE, KONDHWA

EXPERIMENT 10
Implement Dijkstra’s Algorithm.

Title: Implement Dijkstra’s Algorithm.

Aim of Experiment:

Study the implementation of Dijkstra’s Algorithm.

Objective :

This assignment will help the student to know how the implementation of Dijkstra’s Algorithm.

Theory:

Dijkstra algorithm is also called single source shortest path algorithm. It is based on greedy technique. The
algorithm maintains a list visited[ ] of vertices, whose shortest distance from the source is already known.

If visited[1], equals 1, then the shortest distance of vertex i is already known. Initially, visited[i] is marked as,
for source vertex.

At each step, we mark visited[v] as 1. Vertex v is a vertex at shortest distance from the source vertex. At each
step of the algorithm, shortest distance of each vertex is stored in an array distance[ ].

Dijkstra’s Algorithm

1. Create cost matrix C[ ][ ] from adjacency matrix adj[ ][ ]. C[i][j] is the cost of going from vertex i to vertex j.
If there is no edge between vertices i and j then C[i][j] is infinity.

2. Array visited[ ] is initialized to zero.

for(i=0;i<n;i++)

visited[i]=0;

3. If the vertex 0 is the source vertex then visited[0] is marked as 1.

Dept. of E & TC
(2023-24)
SAE, KONDHWA

4. Create the distance matrix, by storing the cost of vertices from vertex no. 0 to n-1 from the source vertex 0.

for(i=1;i<n;i++)

distance[i]=cost[0][i];

Initially, distance of source vertex is taken as 0. i.e. distance[0]=0;

5. for(i=1;i<n;i++)

– Choose a vertex w, such that distance[w] is minimum and visited[w] is 0. Mark visited[w] as 1.

– Recalculate the shortest distance of remaining vertices from the source.

– Only, the vertices not marked as 1 in array visited[ ] should be considered for recalculation of distance. i.e. for
each vertex v

if(visited[v]==0)

distance[v]=min(distance[v],

distance[w]+cost[w][v])

Time Complexity

The program contains two nested loops each of which has a complexity of O(n). n is number of vertices. So the
complexity of algorithm is O(n2).

References :

1. “C programming “ Balguruswamy.
2. ‘Fundamentals of datastructures” sartaj sahani.
3. “Data structures “ Tananbom

Conclusion:

Dept. of E & TC
(2023-24)
SAE, KONDHWA

Program:

//C Program on Dijkstra Algorithm for Finding Minimum Distance of Vertices from a Given Source in a Graph

#include<stdio.h>
#include<conio.h>
#define INFINITY 9999
#define MAX 10

void dijkstra(int G[MAX][MAX],int n,int startnode);

int main()
{
int G[MAX][MAX],i,j,n,u;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");

for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);

printf("\nEnter the starting node:");


scanf("%d",&u);
dijkstra(G,n,u);

return 0;
}

void dijkstra(int G[MAX][MAX],int n,int startnode)


{

int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;

//pred[] stores the predecessor of each node


//count gives the number of nodes seen so far
//create the cost matrix
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];

//initialize pred[],distance[] and visited[]


for(i=0;i<n;i++)
Dept. of E & TC
(2023-24)
SAE, KONDHWA

{
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}

distance[startnode]=0;
visited[startnode]=1;
count=1;

while(count<n-1)
{
mindistance=INFINITY;

//nextnode gives the node at minimum distance


for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{
mindistance=distance[i];
nextnode=i;
}

//check if a better path exists through nextnode


visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
{
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
}
count++;
}

//print the path and distance of each node


for(i=0;i<n;i++)
if(i!=startnode)
{
printf("\nDistance of node%d=%d",i,distance[i]);
printf("\nPath=%d",i);

j=i;
do
{
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}
}
Dept. of E & TC
(2023-24)

You might also like