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

Data Structure Lab Manual

The document describes implementing a stack data structure using an array in C. It includes algorithms for push, pop, and peek operations on the stack. A C program is provided that demonstrates these stack operations through a menu-driven program that allows the user to push, pop, display and exit the stack implementation.

Uploaded by

Ńøøb Gaming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

Data Structure Lab Manual

The document describes implementing a stack data structure using an array in C. It includes algorithms for push, pop, and peek operations on the stack. A C program is provided that demonstrates these stack operations through a menu-driven program that allows the user to push, pop, display and exit the stack implementation.

Uploaded by

Ńøøb Gaming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

DATA STRUCTURE LAB

EXPERIMENT NO-1

Aim: Implement Stack ADT using Array

Software : C

Theory :

In array implementation, the stack is formed by using the array. All the operations regarding
the stack are performed using arrays. Lets see how each operation can be implemented on
the stack using array data structure.

Adding an element onto the stack (push operation)

Adding an element into the top of the stack is referred to as push operation. Push operation
involves following two steps.

Algorithm:

begin

if top = n then stack full

top = top + 1

stack (top) : = item;

end

Deletion of an element from a stack (Pop operation)

Deletion of an element from the top of the stack is called pop operation. The value of the
variable top will be incremented by 1 whenever an item is deleted from the stack. The top
most element of the stack is stored in an another variable and then the top is decremented
by 1. the operation returns the deleted value that was stored in another variable as the
result.

Algorithm :

begin

if top = 0 then stack empty;

item := stack(top);
top = top - 1;

end;

Visiting each element of the stack (Peek operation)


Algorithm :

PEEK (STACK, TOP)

Begin

if top = -1 then stack empty

item = stack[top]

return item

End

C Program:

#include<stdio.h>

int stack[100],choice,n,top,x,i;

void push(void);

void pop(void);

void display(void);

int main()

top=-1;

printf("\n Enter the size of STACK[MAX=100]:");

scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");

printf("\n\t ");

printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");

do

printf("\n Enter the Choice:");

scanf("%d",&choice);

switch(choice)

case 1:

push();

break;

case 2:

pop();

break;

case 3:

display();

break;

case 4:

{
printf("\n\t EXIT POINT ");

break;

default:

printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");

while(choice!=4);

return 0;

void push()

if(top>=n-1)

printf("\n\tSTACK is over flow");

else

printf(" Enter a value to be pushed:");

scanf("%d",&x);

top++;

stack[top]=x;
}

void pop()

if(top<=-1)

printf("\n\t Stack is under flow");

else

printf("\n\t The popped elements is %d",stack[top]);

top--;

void display()

if(top>=0)

printf("\n The elements in STACK \n");

for(i=top; i>=0; i--)

printf("\n%d",stack[i]);

printf("\n Press Next Choice");

else

{
printf("\n The STACK is empty");

OUTPUT:

Enter the size of STACK[MAX=100]:10

STACK OPERATIONS USING ARRAY

1. PUSH

2. POP

3. DISPLAY

4. EXIT

Enter the Choice:1

Enter a value to be pushed:12

Enter the Choice:1

Enter a value to be pushed:24

Enter the Choice:1

Enter a value to be pushed:98

Enter the Choice:3

The elements in STACK

98

24

12

Press Next Choice


Enter the Choice:2

The popped elements is 98

Enter the Choice:3

The elements in STACK

24

12

Press Next Choice

Enter the Choice:4

EXIT POINT

Conclusion: Thus we have implement Stack ADT using Array.


EXPERIMENT NO-2

Aim: Convert an Infix Expression to Postfix Expression using Stack ADT.

Software : C

Theory :

Infix expression: The expression of the form a operator b (a + b). When an operator is in-
between every pair of operands.
Postfix expression: The expression of the form a b operator (ab+). When an operator is
followed by every pair of operands.

Examples:

Input: A + B * C + D
Output: ABC*+D+

Steps to convert Infix expression to Postfix expression using Stack:


Scan the infix expression from left to right.

If the scanned character is an operand, output it.

Else,

If the precedence and associativity of the scanned operator are greater than the
precedence and associativity of the operator in the stack(or the stack is empty or the stack
contains a ‘(‘ ), then push it.

‘^’ operator is right associative and other operators like ‘+’,’-‘,’*’ and ‘/’ are left-
associative. Check especially for a condition when both, operator at the top of the stack
and the scanned operator are ‘^’. In this condition, the precedence of the scanned
operator is higher due to its right associativity. So it will be pushed into the operator stack.
In all the other cases when the top of the operator stack is the same as the scanned
operator, then pop the operator from the stack because of left associativity due to which
the scanned operator has less precedence.

Repeat steps 2-6 until the infix expression is scanned.

Print the output

Pop and output from the stack until it is not empty.


C Program:

#include<stdio.h>
#include<ctype.h>

char stack[100];
int top = -1;

void push(char x)
{
stack[++top] = x;
}

char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}

int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
return 0;
}

int main()
{
char exp[100];
char *e, x;
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
e = exp;

while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c ",pop());
push(*e);
}
e++;
}

while(top != -1)
{
printf("%c ",pop());
}return 0;
}

Output Test Case 1:

Enter the expression : a+b*c

abc*+
EXPERIMENT NO - 3

Aim: Evaluate Postfix Expression using Stack ADT

Software : C

Theory :

Evaluation of Postfix Expression Using Stack:


Follow the steps mentioned below to evaluate postfix expression using stack:

Create a stack to store operands (or values).

Scan the given expression from left to right and do the following for every scanned
element.

If the element is a number, push it into the stack

If the element is an operator, pop operands for the operator from the stack. Evaluate the
operator and push the result back to the stack

When the expression is ended, the number in the stack is the final answer

Algorithm
Postfix Evaluation(postfix)
Input: Postfix expression to evaluate.
Output: Answer after evaluating postfix form.
Begin
for each character ch in the postfix expression, do
if ch is an operator ⨀ , then
a := pop first element from stack
b := pop second element from the stack
res := b ⨀ a
push res into the stack
else if ch is an operand, then
add ch into the stack
done
return element of stack top
End
C Program:

#include<stdio.h>
int stack[20];
int top = -1;

void push(int x)
{
stack[++top] = x;
}

int pop()
{
return stack[top--];
}

int main()
{
char exp[20];
char *e;
int n1,n2,n3,num;
printf("Enter the expression :: ");
scanf("%s",exp);
e = exp;
while(*e != '\0')
{
if(isdigit(*e))
{
num = *e - 48;
push(num);
}
else
{
n1 = pop();
n2 = pop();
switch(*e)
{
case '+':
{
n3 = n1 + n2;
break;
}
case '-':
{
n3 = n2 - n1;
break;
}
case '*':
{
n3 = n1 * n2;
break;
}
case '/':
{
n3 = n2 / n1;
break;
}
}
push(n3);
}
e++;
}
printf("\nThe result of expression %s = %d\n\n",exp,pop());
return 0;
}

OUTPUT:
Enter the expression :: 245+*

The result of expression 245+* = 18


EXPERIMENT NO – 4

Aim: Implement Doubly Linked List

Software : C

Theory :

Doubly Linked List is a variation of Linked list in which navigation is possible in both ways,
either forward and backward easily as compared to Single Linked List. Following are the
important terms to understand the concept of doubly linked list.

Link − Each link of a linked list can store a data called an element.

Next − Each link of a linked list contains a link to the next link called Next.

Prev − Each link of a linked list contains a link to the previous link called Prev.

LinkedList − A Linked List contains the connection link to the first link called First and to the
last link called Last.

In C, structure of a node in doubly linked list can be given as :

struct node
{

struct node *prev;

int data;

struct node *next;

Basic Operations

Following are the basic operations supported by a list.

Insertion − Adds an element at the beginning of the list.

Deletion − Deletes an element at the beginning of the list.

Insert Last − Adds an element at the end of the list.

Delete Last − Deletes an element from the end of the list.

Insert After − Adds an element after an item of the list.

Delete − Deletes an element from the list using the key.

Display forward − Displays the complete list in a forward manner.

Display backward − Displays the complete list in a backward manner.

Insertion in DLL:
At the front of the DLL

After a given node.

At the end of the DLL

1) Add a node at the front:

The new node is always added before the head of the given Linked List. And newly added
node becomes the new head of DLL. For example, if the given Linked List is 1->0->1->5 and
we add an item 5 at the front, then the Linked List becomes 5->1->0->1->5.
2) Add a node after a given node:

We are given a pointer to a node as prev_node, and the new node is inserted after the
given node.

3) Add a node at the end:

The new node is always added after the last node of the given Linked List. For example, if
the given DLL is 5->1->0->1->5->2 and we add item 30 at the end, then the DLL becomes 5-
>1->0->1->5->2->30.
Implement Doubly Linked List ADT
#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#include <stdbool.h>

struct node {

int data;

int key;

struct node *next;

struct node *prev;

};

//this link always point to first Link

struct node *head = NULL;

//this link always point to last Link

struct node *last = NULL;

struct node *current = NULL;

//is list empty

bool isEmpty() {

return head == NULL;

int length() {

int length = 0;

struct node *current;

for(current = head; current != NULL; current = current->next){


length++;

return length;

//display the list in from first to last

void displayForward() {

//start from the beginning

struct node *ptr = head;

//navigate till the end of the list

printf("\n[ ");

while(ptr != NULL) {

printf("(%d,%d) ",ptr->key,ptr->data);

ptr = ptr->next;

printf(" ]");

//display the list from last to first

void displayBackward() {

//start from the last

struct node *ptr = last;

//navigate till the start of the list

printf("\n[ ");

while(ptr != NULL) {

//print data

printf("(%d,%d) ",ptr->key,ptr->data);

//move to next item


ptr = ptr ->prev;

//insert link at the first location

void insertFirst(int key, int data) {

//create a link

struct node *link = (struct node*) malloc(sizeof(struct node));

link->key = key;

link->data = data;

if(isEmpty()) {

//make it the last link

last = link;

} else {

//update first prev link

head->prev = link;

//point it to old first link

link->next = head;

//point first to new first link

head = link;

//insert link at the last location

void insertLast(int key, int data) {

//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));

link->key = key;

link->data = data;

if(isEmpty()) {

//make it the last link

last = link;

} else {

//make link a new last link

last->next = link;

//mark old last node as prev of new link

link->prev = last;

//point last to new last node

last = link;

//delete first item

struct node* deleteFirst() {

//save reference to first link

struct node *tempLink = head;

//if only one link

if(head->next == NULL){

last = NULL;

} else {

head->next->prev = NULL;

}
head = head->next;

//return the deleted link

return tempLink;

//delete link at the last location

struct node* deleteLast() {

//save reference to last link

struct node *tempLink = last;

//if only one link

if(head->next == NULL) {

head = NULL;

} else {

last->prev->next = NULL;

last = last->prev;

//return the deleted link

return tempLink;

//delete a link with given key

struct node* delete(int key) {

//start from the first link

struct node* current = head;

struct node* previous = NULL;

//if list is empty

if(head == NULL) {

return NULL;
}

//navigate through list

while(current->key != key) {

//if it is last node

if(current->next == NULL) {

return NULL;

} else {

//store reference to current link

previous = current;

//move to next link

current = current->next;

//found a match, update the link

if(current == head) {

//change first to point to next link

head = head->next;

} else {

//bypass the current link

current->prev->next = current->next;

if(current == last) {

//change last to point to prev link

last = current->prev;

} else {

current->next->prev = current->prev;
}

return current;

bool insertAfter(int key, int newKey, int data) {

//start from the first link

struct node *current = head;

//if list is empty

if(head == NULL) {

return false;

//navigate through list

while(current->key != key) {

//if it is last node

if(current->next == NULL) {

return false;

} else {

//move to next link

current = current->next;

//create a link

struct node *newLink = (struct node*) malloc(sizeof(struct node));

newLink->key = newKey;

newLink->data = data;

if(current == last) {
newLink->next = NULL;

last = newLink;

} else {

newLink->next = current->next;

current->next->prev = newLink;

newLink->prev = current;

current->next = newLink;

return true;

void main() {

insertFirst(1,10);

insertFirst(2,20);

insertFirst(3,30);

insertFirst(4,1);

insertFirst(5,40);

insertFirst(6,56);

printf("\nList (First to Last): ");

displayForward();

printf("\n");

printf("\nList (Last to first): ");

displayBackward();

printf("\nList , after deleting first record: ");


deleteFirst();

displayForward();

printf("\nList , after deleting last record: ");

deleteLast();

displayForward();

printf("\nList , insert after key(4) : ");

insertAfter(4,7, 13);

displayForward();

printf("\nList , after delete key(4) : ");

delete(4);

displayForward();

Output
List (First to Last):
[ (6,56) (5,40) (4,1) (3,30) (2,20) (1,10) ]

List (Last to first):


[ (1,10) (2,20) (3,30) (4,1) (5,40) (6,56) ]
List , after deleting first record:
[ (5,40) (4,1) (3,30) (2,20) (1,10) ]
List , after deleting last record:
[ (5,40) (4,1) (3,30) (2,20) ]
List , insert after key(4) :
[ (5,40) (4,1) (7,13) (3,30) (2,20) ]
List , after delete key(4) :
[ (5,40) (4,13) (3,30) (2,20) ]
EXPERIMENT NO – 5

Aim: Application of stack ADT

Software : C

Theory:

Stack is a linear data structure that holds a linear, ordered sequence of elements. It
is an abstract data type. A Stack works on the LIFO process (Last In First Out), i.e.,
the element that was inserted last will be removed first. To implement the Stack, it is
required to maintain a pointer to the top of the Stack, which is the last element to be
inserted because we can access the elements only on the top of the Stack.
Operation on Stack

1. PUSH: PUSH operation implies the insertion of a new element into a Stack. A new
element is always inserted from the topmost position of the Stack; thus, we always
need to check if the top is empty or not, i.e., TOP=Max-1 if this condition goes false,
it means the Stack is full, and no more elements can be inserted, and even if we try
to insert the element, a Stack overflow message will be displayed.

Algorithm:

Step-1: If TOP = Max-1

Print “Overflow”

Goto Step 4

Step-2: Set TOP= TOP + 1

Step-3: Set Stack[TOP]= ELEMENT

Step-4: END

2. POP: POP means to delete an element from the Stack. Before deleting an
element, make sure to check if the Stack Top is NULL, i.e., TOP=NULL. If this
condition goes true, it means the Stack is empty, and no deletion operation can be
performed, and even if we try to delete, then the Stack underflow message will be
generated.
Algorithm:

Step-1: If TOP= NULL

Print “Underflow”

Goto Step 4

Step-2: Set VAL= Stack[TOP]

Step-3: Set TOP= TOP-1

Step-4: END

3. PEEK: When we need to return the value of the topmost element of the Stack
without deleting it from the Stack, the Peek operation is used. This operation first
checks if the Stack is empty, i.e., TOP = NULL; if it is so, then an appropriate
message will display, else the value will return.

Algorithm:

Step-1: If TOP = NULL

PRINT “Stack is Empty”

Goto Step 3

Step-2: Return Stack[TOP]

Step-3: END
EXPERIMENT NO-6

Aim: Implement Linear Queue ADT using Linked List.

Software : C

Theory :

A queue is a linear data structure that follows the First In, First Out (FIFO) principle, which
means that the element which is inserted first in the queue will be the first one to be
removed from the queue. A good example of a queue is a queue of customers purchasing a
train ticket, where the customer who comes first will be served first.

A linked queue is shown here:

Operation on Linked Queue:


The two main operations performed on the linked queue are:

Insertion

Insert operation or insertion on a linked queue adds an element to the end of the queue.
The new element which is added becomes the last element of the queue.

Create a new node pointer.


ptr = (struct node *) malloc (sizeof(struct node));

*ptr - > data = val;

if (front == NULL) {

front = ptr;

rear = ptr;

front - > next = NULL;

rear - > next = NULL;

}
Deletion

Deletion or delete operation on a linked queue removes the element which was first
inserted in the queue, i.e., always the first element of the queue is removed.

Steps to perform Deletion on a linked queue:

Check if the queue is empty or not.

If the queue is empty, i.e., front==NULL, so we just print 'underflow' on the screen and exit.

If the queue is not empty, delete the element at which the front pointer is pointing. For
deleting a node, copy the node which is pointed by the front pointer into the pointer ptr and
make the front pointer point to the front's next node and free the node pointed by the node
ptr. This can be done using the following statement:

*ptr = front;

front = front -> next;

free(ptr);

Steps for implementing queue using linked list:

1. Enqueue Function

Enqueue function adds an element to the end of the queue. It takes O(1) time. The last
element can be tracked using the rear pointer.

First, build a new node with given data.

Check if the queue is empty or not.

If a queue is empty then, a new node is assigned to the front and rear.

Else make next of rear as new node and rear as a new node.

2. Dequeue Function

The dequeue function always removes the first element of the queue. It takes O(1) time. For
dequeue, the queue must contain at least one element, else underflow conditions will
occur.

Check if queue is empty or not.

If the queue is empty, then dequeue is not possible.


Else store front in temp

And make next of front as the front.

Delete temp, i.e, free(temp).

C Program:

#include < stdio.h >

#include < stdlib.h >

// Structure to create a node with data and the next pointer

struct node {

int data;

struct node * next;

};

struct node * front = NULL;

struct node * rear = NULL;

// Enqueue() operation on a queue

void enqueue(int value) {

struct node * ptr;


ptr = (struct node * ) malloc(sizeof(struct node));

ptr - > data = value;

ptr - > next = NULL;

if ((front == NULL) && (rear == NULL)) {

front = rear = ptr;

} else {

rear - > next = ptr;

rear = ptr;

printf("Node is Inserted\n\n");

// Dequeue() operation on a queue

int dequeue() {

if (front == NULL) {

printf("\nUnderflow\n");

return -1;

} else {

struct node * temp = front;

int temp_data = front - > data;

front = front - > next;

free(temp);

return temp_data;

// Display all elements of the queue


void display() {

struct node * temp;

if ((front == NULL) && (rear == NULL)) {

printf("\nQueue is Empty\n");

} else {

printf("The queue is \n");

temp = front;

while (temp) {

printf("%d--->", temp - > data);

temp = temp - > next;

printf("NULL\n\n");

int main() {

int choice, value;

printf("\nImplementation of Queue using Linked List\n");

while (choice != 4) {

printf("1.Enqueue\n2.Dequeue\n3.Display\n4.Exit\n");

printf("\nEnter your choice : ");

scanf("%d", & choice);

switch (choice) {

case 1:

printf("\nEnter the value to insert: ");

scanf("%d", & value);


enqueue(value);

break;

case 2:

printf("Popped element is :%d\n", dequeue());

break;

case 3:

display();

break;

case 4:

exit(0);

break;

default:

printf("\nWrong Choice\n");

return 0;

Output:

Enqueue Operation:
Implementation of Queue using Linked List

1. Enqueue

2. Dequeue

3. Display
4. Exit

Enter your choice: 1

Enter the value to insert: 12

Node is Inserted

1.Enqueue

2.Dequeue

3.Display

4.Exit

Enter your choice: 1

Enter the value to insert: 45

Node is Inserted

1.Enqueue

2.Dequeue

3.Display

4.Exit

Enter your choice: 1

Enter the value to insert: 56

Node is Inserted
1.Enqueue

2.Dequeue

3.Display

4.Exit

Enter your choice : 3

The queue is

12--->45--->56--->NULL

Dequeue Operation:
The queue is

12--->45--->56--->NULL

1.Enqueue

2.Dequeue

3.Display

4.Exit

Enter your choice: 2

Popped element is:12

1. Enqueue

2. Dequeue

3. Display

4. Exit
Enter your choice: 2

Popped element is:45

1. Enqueue

2. Dequeue

3. Display

4. Exit

Enter your choice : 3

The queue is

56--->NULL

1.Enqueue

2.Dequeue

3.Display

4.Exit

Enter your choice: 2

Popped element is:56

1. Enqueue

2. Dequeue

3. Display

4. Exit
Experiment No--7

Aim: Implement circular queue ADT using array

Software : C

Program:

#include<stdio.h>

#define max 5

int front = -1, rear = -1; // global variable

int CQueue[max];

void insert();

int delete();

void display();

int main() {

int w, no;

for (;;) {

printf("\n1. Insert");

printf("\n2. Delete");

printf("\n3. Display");

printf("\n4. EXIT");

printf("\nEnter what you want :");

scanf("%d", & w);

switch (w) {

case 1:

insert();

break;
case 2:

no = delete();

break;

case 3:

display();

break;

case 4:

exit(1);

default:

printf("\nInvalid Choice !!\n");

void insert() {

int no;

if ((front == 0 && rear == max - 1) || front == rear + 1) {

printf("\nCircular Queue Is Full !\n");

return;

printf("\nEnter a number to Insert :");

scanf("%d", & no);

if (front == -1)

front = front + 1;

if (rear == max - 1)

rear = 0;
else rear = rear + 1;

CQueue[rear] = no;

int delete() {

int e;

if (front == -1) {

printf("\nThe Circular Queue is Empty !!\n");

e = CQueue[front];

if (front == max - 1)

front = 0;

else if (front == rear) {

front = -1;

rear = -1;

} else front = front + 1;

printf("\n%d was deleted !\n", e);

return e;

void display() {

int i;

if (front == -1) {

printf("\nThe Circular Queue is Empty ! Nothing To Display !!\n");

return;
}

i = front;

if (front <= rear) {

printf("\n\n");

while (i <= rear)

printf("%d ", CQueue[i++]);

printf("\n");

} else {

printf("\n\n");

while (i <= max - 1)

printf("%d ", CQueue[i++]);

i = 0;

while (i <= rear)

printf("%d ", CQueue[i++]);

printf("\n");

}
Experiment No--8

Aim: Implement singly link list in ADT

Software : C

Theory: t is a type of linked list in which traversing occurs only in one direction from the
head to the end node. Every node contains data and the pointer which contains the
address of the next node.

Example:
The most common type of linked list is a single linked list. A singly linked list can only be
traversed in one direction. Each node in a singly linked list has data as well as a pointer
to the next node.

Program:

#include <stdio.h>

#include <stdlib.h>

//Self referential structure to create node.

typedef struct tmp

int item;

struct tmp * next;

}Node;

//structure for create linked list.

typedef struct
{Node * head;

Node * tail;

}List;

//Initialize List

void initList(List * lp)

lp->head = NULL;

lp->tail = NULL;

//Create node and return reference of it.

Node * createNode(int item)

Node * nNode;

nNode = (Node *) malloc(sizeof(Node));

nNode->item = item;

nNode->next = NULL;

return nNode;

//Add new item at the end of list.

void addAtTail(List * lp,int item)

Node * node;

node = createNode(item);
//if list is empty.

if(lp->head == NULL)

lp->head = node;

lp->tail = node;

else

lp->tail->next = node;

lp->tail = lp->tail->next;

//Delete item from the end of list.

int delFromTail(List * lp)

Node * temp;

int i = 0;

int item = 0;

if(lp->tail == NULL)

printf("\nList is Empty ...");

return -1;

else

temp = lp->head
while(temp->next != lp->tail)

{ temp = temp->next;}

item = lp->tail->item;

lp->tail = temp;

lp->tail->next = NULL;

return item;

//Add new item at begning of the list.

void addAtHead(List * lp,int item)

Node * node;

node = createNode(item);

//if list is empty.

if(lp->head == NULL)

lp->head = node;

lp->tail = node;

else

node->next = lp->head ;

lp->head = node ;
}}

//Delete item from Start of list.

int delFromHead(List * lp)

int item = 0;

if(lp->head == NULL)

printf("\nList is Empty ...");

return -1;

else

item = lp->head->item;

lp->head = lp->head->next;

return item;

//To print list from start to end of the list.

void printList(List *lp)

Node * node;

if(lp->head == NULL)

{printf("\nEmpty List");
return;

node = lp->head;

printf("\nList: \n\n\t");

while(node != NULL)

printf("| %05d |",node->item);

node = node->next;

if(node !=NULL)

printf("--->");

printf("\n\n");

//Main function to execute program.

int main()

List *lp;

int item = 0;

lp = (List *) malloc(sizeof(List));

initList(lp);

addAtTail(lp,10);

addAtTail(lp,20);
addAtHead(lp,30);

addAtHead(lp,40);

printList(lp);

item = delFromTail(lp);

if(item >= 0)

printf("\nDeleted item is : %d",item);

printList(lp);

item = delFromHead(lp);

if(item >= 0)

printf("\nDeleted item is : %d",item);

printList(lp);

return 0;

}
EXPERIMENT NO-9

Aim: Implement Graph Traversal Techniques : Depth First Search

Software : C

Theory :

Graph traversal is a technique used for a searching vertex in a graph. The graph traversal is
also used to decide the order of vertices is visited in the search process. A graph traversal
finds the edges to be used in the search process without creating loops. That means using
graph traversal we visit all the vertices of the graph without getting into looping path.

There are two graph traversal techniques and they are as follows...

DFS (Depth First Search)

BFS (Breadth First Search)

DFS (Depth First Search)

DFS traversal of a graph produces a spanning tree as final result. Spanning Tree is a graph
without loops. We use Stack data structure with maximum size of total number of vertices
in the graph to to implement DFS traversal.

We use the following steps to implement DFS traversal...

Step 1 - Define a Stack of size total number of vertices in the graph.

Step 2 - Select any vertex as starting point for traversal. Visit that vertex and push it on to
the Stack.

Step 3 - Visit any one of the non-visited adjacent vertices of a vertex which is at the top of
stack and push it on to the stack.

Step 4 - Repeat step 3 until there is no new vertex to be visited from the vertex which is at
the top of the stack.

Step 5 - When there is no new vertex to visit then use back tracking and pop one vertex
from the stack.

Step 6 - Repeat steps 3, 4 and 5 until stack becomes Empty.

Step 7 - When stack becomes Empty, then produce final spanning tree by removing unused
edges from the graph
C Program:

// C code to implement above approach

#include <stdio.h>

#include <stdlib.h>

// Globally declared visited array

int vis[100];

// Graph structure to store number

// of vertices and edges and

// Adjacency matrix

struct Graph {

int V;

int E;

int** Adj;

};

// Function to input data of graph

struct Graph* adjMatrix()

struct Graph* G = (struct Graph*)

malloc(sizeof(struct Graph));

if (!G) {

printf("Memory Error\n");

return NULL;

G->V = 7;
G->E = 7;

G->Adj = (int**)malloc((G->V) * sizeof(int*));

for (int k = 0; k < G->V; k++) {

G->Adj[k] = (int*)malloc((G->V) * sizeof(int));

for (int u = 0; u < G->V; u++) {

for (int v = 0; v < G->V; v++) {

G->Adj[u][v] = 0;

G->Adj[0][1] = G->Adj[1][0] = 1;

G->Adj[0][2] = G->Adj[2][0] = 1;

G->Adj[1][3] = G->Adj[3][1] = 1;

G->Adj[1][4] = G->Adj[4][1] = 1;

G->Adj[1][5] = G->Adj[5][1] = 1;

G->Adj[1][6] = G->Adj[6][1] = 1;

G->Adj[6][2] = G->Adj[2][6] = 1;

return G;

// DFS function to print DFS traversal of graph

void DFS(struct Graph* G, int u)

{
vis[u] = 1;

printf("%d ", u);

for (int v = 0; v < G->V; v++) {

if (!vis[v] && G->Adj[u][v]) {

DFS(G, v);

// Function for DFS traversal

void DFStraversal(struct Graph* G)

for (int i = 0; i < 100; i++) {

vis[i] = 0;

for (int i = 0; i < G->V; i++) {

if (!vis[i]) {

DFS(G, i);

// Driver code

void main()

struct Graph* G;
G = adjMatrix();

DFStraversal(G);

}
EXPERIMENT NO-10

Aim: Implement Graph Traversal Techniques Breadth First search

Software : C

Theory :

BFS(Breadth First search)

BFS is the most commonly used approach. It is a recursive algorithm to search all the
vertices of a tree or graph data structure. BFS puts every vertex of the graph into two
categories - visited and non-visited. It selects a single node in a graph and, after that, visits
all the nodes adjacent to the selected node.

We use the following steps to implement BFS traversal...

Step 1 - Define a Queue of size total number of vertices in the graph.

Step 2 - Select any vertex as starting point for traversal. Visit that vertex and insert it into
the Queue.

Step 3 - Visit all the non-visited adjacent vertices of the vertex which is at front of the
Queue and insert them into the Queue.

Step 4 - When there is no new vertex to be visited from the vertex which is at front of the
Queue then delete that vertex.

Step 5 - Repeat steps 3 and 4 until queue becomes empty.

Step 6 - When queue becomes empty, then produce final spanning tree by removing unused
edges from the graph.

C Program:

#include <stdio.h>

int n, i, j, visited[10], queue[10], front = -1, rear = -1;

int adj[10][10];

void bfs(int v)

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


if (adj[v][i] && !visited[i])

queue[++rear] = i;

if (front <= rear)

visited[queue[front]] = 1;

bfs(queue[front++]);

void main()

int v;

printf("Enter the number of vertices: ");

scanf("%d", &n);

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

queue[i] = 0;

visited[i] = 0;

printf("Enter graph data in matrix form: \n");

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

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

scanf("%d", &adj[i][j]);

printf("Enter the starting vertex: ");

scanf("%d", &v);

bfs(v);
printf("The node which are reachable are: \n");

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

if (visited[i])

printf("%d\t", i);

else

printf("BFS is not possible. Not all nodes are reachable");

return 0;

You might also like