You are on page 1of 44

HIMGIRI ZEE UNIVERSITY

Department of Computer Science and Engineering

Year:1st Semester:1st SEM

Advanced Data Structures – MTech CSE-503

LAB MANUAL

Submitted to: Submitted by:


Mr. Rakesh Arya Deepti Kuthari
Head Of Department Mtech(CSE) 1st sem
Dept. of CS&IT HZU20210321
HIMGIRI ZEE UNIVERSITY
Department of Computer Science and Engineering

INDEX

S.No Practical’s Name Date Remark


1 Array and Linked list implementation of List ADT.
2 Array and Linked list implementation of Stack ADT.

3 Applications of List, Stack and Queue ADTs.


4 Implementation of Binary trees and operations of
Binary trees.
5 Implementation of Binary Search Trees.
6 Implementation of AVL Trees.
7 Implementation of Heaps using Priority Queues.
8 Graph representation and Traversal algorithms.
9 Given the eight queens puzzle problem of placing
eight chess queens on an 8×8 chessboard so that no
two queens attack each other

10 Given a queue of four elements, the program


successfully executed concurrent linked Queues.

11 To find out the Maximum flow and Minimum cut in a


graph for any given number of nodes.
Program 1. Array and Linked list implementation of List ADT.
// C Program to implementation of List ADT as Array.
“Larray.h” File:
#include<stdio.h>
#include<alloc.h>
#include<conio.h>
struct list
{
  int capacity;
  int size;
  int *array;
};
typedef struct list *ptrToNode;
typedef ptrToNode LIST;
typedef int POSITION;

int Isempty(LIST L)
{
return L->size==0;
}

void MakeEmpty(LIST L)
{
if(Isempty(L))
   printf("\n LIST is already Empty");
else
   {
      L->size=0;
      printf("\n Now List becomes Empty");
   }
}

LIST Createlist(int max)


{
LIST L;
L=(struct list*)malloc(sizeof(struct list));
if(L==NULL)
   printf("\n Fatal Error");
else
{
   L->capacity=max;
   L->array=(int*)malloc(sizeof(int)*max);
   if(L->array==NULL)
      printf("\n Fatal Error");
   else
   {
      L->size=0;
      printf("\n List is Created successfully");
   }
}
return L;
}

int Isfull(LIST L)
{
return L->size==L->capacity;
}

void Insert(int x,LIST L,POSITION P)


{
int i;
if(Isfull(L))
   printf("\n List is Full");
else
   {
      for(i=L->size-1;i>=P;i--)
      L->array[i+1]=L->array[i];
      L->size++;
      L->array[P]=x;
   }
}

POSITION Findprevious(int x,LIST L)


{
POSITION P;
P=-1;
while(P!=L->size&&L->array[P+1]!=x)
{
   P++;
}
return P;
}

POSITION Find(int x,LIST L)


{
POSITION P;
P=0;
while(P!=L->size&&L->array[P]!=x)
{
   P++;
}
return P;
}

void Delete(int x,LIST L)


{
int i;
POSITION P;
P=Find(x,L);
if(P==L->size)
   printf("\n Element not found in the list");
else
   {
      for(i=P;i<L->size;i++)

      L->array[i]=L->array[i+1];
      L->size--;
   }
}

LIST Deletelist(LIST L)
{
MakeEmpty(L);
free(L);
L=NULL;
return L;
}

void Display(LIST L)
{
int i;
for(i=0;i<L->size;i++)
printf("\n %d",L->array[i]);
}

“Larray.c” File:

#include"Larray.h"
#include<stdlib.h>
void main()
{
LIST L=NULL;
POSITION P;
int a,choice,ch,element;
clrscr();
printf("\n\n1.Create\n2.Insert\n3.Delete\n4.Display\n5.MakeEmpty\n6.Find\n7.IsEmpty\n8.IsFull\n9.Deletelist\
n10.Exit\n");
A:
printf("\n Enter Ur Option:\t");
scanf("%d",&choice);
switch(choice)
{
case 1:
    if(L==NULL)
       L=Createlist(5);
    else
       printf("\nList is already created");
    break;
case 2:
    if(L==NULL)
       printf("\nList is not yet created");
    else
    {
       printf("\nEnter the Element to insert:\t");
       scanf("%d",&element);
       if(L->size==0)
          Insert(element,L,0);

       else
       {
          printf("\n where u want to insert?\t1:Front\t2:Back\t3:middle\t::: ");
          scanf("%d",&ch);
          if(ch==1)
         Insert(element,L,0);
          else
          if(ch==2)
         Insert(element,L,L->size);
          else
          if(ch==3)
          {
         printf("\nWhere you want to insert:\t");
         scanf("%d",&a);
         P=Find(a,L);
         if(P<L->size)
            Insert(element,L,P);
         else
            printf("\nElement is not in the list");
           }
           else
           printf("\n Ur choice is not available");
         }
    }
    break;
case 3:
    if(L==NULL)
       printf("\nList is not yet created");
    if(Isempty(L))
       printf("\nList is empty");
    else
    {
       printf("\nEnter the element to delete:\t");
       scanf("%d",&a);
       Delete(a,L);
    }
    break;
case 4:
    if(L==NULL)
       printf("\nList is not yet created");
    else
    if(Isempty(L))
       printf("\nList is empty");
    else
    {
       printf("\nElements present in the list are:");
       Display(L);
    }
    break;
case 5:
    if(L==NULL)
       printf("\n List is not yet created ");

    else
       MakeEmpty(L);
    break;
case 6:
    if(L==NULL)
       printf("\n Not yet created");
    else
       if(Isempty(L))
          printf("\n List is empty");
       else
       {
          printf("\n which element is to find:\t");
          scanf("%d",&a);
          P=Find(a,L);
          printf("\n Element is at %d\t[0 to 4 means present]\t[5 means not present]",P);
       }
    break;
case 7:
    if(L==NULL)
       printf("\n Not yet created");
    else
       if(Isempty(L))
          printf("\n List is empty");
       else
          printf("\n List is not empty");
    break;
case 8:
    if(L==NULL)
       printf("\n Not yet created");
    else
       if(Isfull(L))
          printf("\n List is FULL");
       else
          printf("\n List is not FULL");
    break;
case 9:
    if(L==NULL)
       printf("\n Not yet created");
    else
    {
       L=Deletelist(L);
       printf("\n List is Deleted");
    }
    break;
case 10:
    exit (0);
    break;
default:
    printf("\n\n *******WRONG ENTRY*******");
    break;
}
goto A;
}

OUTPUT:

1.Create
2.Insert
3.Delete
4.Display
5.MakeEmpty
6.Find
7.IsEmpty
8.IsFull
9.Deletelist
10.Exit

Enter Ur Option:    1
List is created successfully
Enter Ur Option:    2
Enter the element to insert:    300

Enter Ur Option:    2
Enter the element to insert:    100
Where U want to insert?    1.Front    2.Back   3.Middle    :::::    1

Enter Ur Option:    2
Enter the element to insert:    200
Where U want to insert?    1.Front    2.Back   3.Middle    :::::    3

Enter Ur Option:    2
Enter the element to insert:    400
Where U want to insert?    1.Front    2.Back   3.Middle    :::::    2

Enter Ur Option:    2
Enter the element to insert:    500
Where U want to insert?    1.Front    2.Back   3.Middle    :::::    2

Enter Ur Option:    2
Enter the element to insert:    600
Where U want to insert?    1.Front    2.Back   3.Middle    :::::    1
List is Full

Enter Ur Option:    4
Elements present in the list are
100
200
300
400
500

Enter Ur Option:    7
List is not empty

Enter Ur Option:    6
Which element is to find:    500
Element at  4    [0 to 4 – present]    [5 – not present]

Enter Ur Option:    3
Enter the element to delete:    300

Enter Ur Option:    4
Elements present in the list are:
100
200
400
500

Enter Ur Option:    8
List is not Full
Enter Ur Option:    5
Now List becomes Empty

Enter Ur Option:    9
List is Deleted

Enter Ur Option:    2
List is not yet created

Enter Ur Option:    12
*******WRONG ENTRY*******

Enter Ur Option:    10
// C Program to implementation of List ADT as linked-list

#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "List.h"

typedef struct ListNode {


Item value;
struct ListNode *next;
} ListNode;

typedef struct ListRep {


ListNode *first; // ptr to first node
ListNode *last; // ptr to last node
} ListRep;

// create new empty list


List newList()
{
List L;
L = malloc(sizeof(ListRep));
assert(L != NULL);
L->first = NULL;
L->last = NULL;
return L;
}

// free memory used by list


void dropList(List L)
{
assert(L != NULL);
ListNode *curr, *next;
curr = L->first;
while (curr != NULL) {
next = curr->next;
dropItem(curr->value);
free(curr);
curr = next;
}
free(L);
}
// display as [1,2,3,4...]
void showList(List L)
{
assert(L != NULL);
ListNode *curr = L->first;
printf("[");
while (curr != NULL) {
ItemShow(curr->value);
if (curr->next != NULL)
printf(",");
}
printf("]");
}

// add item into list


// no check for duplicates
void ListInsert(List L, Item it)
{
assert(L != NULL);
ListNode *new = malloc(sizeof(ListNode));
assert(new != NULL);
new->value = it;
new->next = NULL;
if (L->last == NULL)
L->first = L->last = new;
else {
ListNode *prev, *curr;
prev = NULL; curr = L->first;
while(curr != NULL){
if(curr->value > new->value){
new->next = curr;
if(prev != NULL){
prev->next = new;
}else{
L->first = new;
}
return;
}
}
prev->next = new;
L->last = new;
}
}

// remove item(s)
// assumes no duplicates
void ListDelete(List L, Key k)
{
assert(L != NULL);
ListNode *prev, *curr;
prev = NULL; curr = L->first;
while (curr != NULL) {
if (eq(k,key(curr->value)))
break;
prev = curr;
curr = curr->next;
}
if (curr != NULL) {
if (prev == NULL)
L->first = curr->next;
else
prev->next = curr->next;
free(curr);
if (L->first == NULL)
L->last = NULL;
}
}

// return item with key


Item *ListSearch(List L, Key k)
{
assert(L != NULL);
ListNode *curr = L->first;
while (curr != NULL) {
if (cmp(k,key(curr->value))== 0) {
return &(curr->value);
} else if (less(k,key(curr->value))) {
curr = curr->next;
}else{
return NULL; // key not found
}
}
return NULL;
}

// # items in list
int ListLength(List L)
{
int n = 0;
ListNode *curr = L->first;
while (curr != NULL) {
n++;
curr = curr->next;
}
return n;
}

Program 2: Array and Linked list implementation of Stack ADT.


// C Program to implementation of Stack ADT as Array.
#include<stdio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
//clrscr();
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

// C Program to implementation of Stack ADT using Linked List.


#include <stdio.h>
#include <stdlib.h>
 
struct node
{
int info;
struct node *ptr;
}*top,*top1,*temp;
 
int topelement();
void push(int data);
void pop();
void empty();
void display();
void destroy();
void stack_count();
void create();
 
int count = 0;
 
void main()
{
int no, ch, e;
 
printf("\n 1 - Push");
printf("\n 2 - Pop");
printf("\n 3 - Top");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Dipslay");
printf("\n 7 - Stack Count");
printf("\n 8 - Destroy stack");
 
create();
 
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
 
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
push(no);
break;
case 2:
pop();
break;
case 3:
if (top == NULL)
printf("No elements in stack");
else
{
e = topelement();
printf("\n Top element : %d", e);
}
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
stack_count();
break;
case 8:
destroy();
break;
default :
printf(" Wrong choice, Please enter correct choice ");
break;
}
}
}
 
/* Create empty stack */
void create()
{
top = NULL;
}
 
/* Count stack elements */
void stack_count()
{
printf("\n No. of elements in stack : %d", count);
}
 
/* Push data into stack */
void push(int data)
{
if (top == NULL)
{
top =(struct node *)malloc(1*sizeof(struct node));
top->ptr = NULL;
top->info = data;
}
else
{
temp =(struct node *)malloc(1*sizeof(struct node));
temp->ptr = top;
temp->info = data;
top = temp;
}
count++;
}
 
/* Display stack elements */
void display()
{
top1 = top;
 
if (top1 == NULL)
{
printf("Stack is empty");
return;
}
 
while (top1 != NULL)
{
printf("%d ", top1->info);
top1 = top1->ptr;
}
}
 
/* Pop Operation on stack */
void pop()
{
top1 = top;
 
if (top1 == NULL)
{
printf("\n Error : Trying to pop from empty stack");
return;
}
else
top1 = top1->ptr;
printf("\n Popped value : %d", top->info);
free(top);
top = top1;
count--;
}
 
/* Return top element */
int topelement()
{
return(top->info);
}
 
/* Check if stack is empty or not */
void empty()
{
if (top == NULL)
printf("\n Stack is empty");
else
printf("\n Stack is not empty with %d elements", count);
}
 
/* Destroy entire stack */
void destroy()
{
top1 = top;
 
while (top1 != NULL)
{
top1 = top->ptr;
free(top);
top = top1;
top1 = top1->ptr;
}
free(top1);
top = NULL;
 
printf("\n All stack elements destroyed");
count = 0;
}
$ cc pgm2.c
$ a.out
 
1 - Push
2 - Pop
3 - Top
4 - Empty
5 - Exit
6 - Dipslay
7 - Stack Count
8 - Destroy stack
Enter choice : 1
Enter data : 56
 
Enter choice : 1
Enter data : 80
 
Enter choice : 2
 
Popped value : 80
Enter choice : 3
 
Top element : 56
Enter choice : 1
Enter data : 78
 
Enter choice : 1
Enter data : 90
 
Enter choice : 6
90 78 56
Enter choice : 7
 
No. of elements in stack : 3
Enter choice : 8
 
All stack elements destroyed
Enter choice : 4
 
Stack is empty
Enter choice : 5

Program 3: C program to implement Applications of List, Stack and Queue ADTs.

// C Program to implementation of List ADT as linked-list

#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "List.h"

typedef struct ListNode {


Item value;
struct ListNode *next;
} ListNode;

typedef struct ListRep {


ListNode *first; // ptr to first node
ListNode *last; // ptr to last node
} ListRep;

// create new empty list


List newList()
{
List L;
L = malloc(sizeof(ListRep));
assert(L != NULL);
L->first = NULL;
L->last = NULL;
return L;
}

// free memory used by list


void dropList(List L)
{
assert(L != NULL);
ListNode *curr, *next;
curr = L->first;
while (curr != NULL) {
next = curr->next;
dropItem(curr->value);
free(curr);
curr = next;
}
free(L);
}

// display as [1,2,3,4...]
void showList(List L)
{
assert(L != NULL);
ListNode *curr = L->first;
printf("[");
while (curr != NULL) {
ItemShow(curr->value);
if (curr->next != NULL)
printf(",");
}
printf("]");
}

// add item into list


// no check for duplicates
void ListInsert(List L, Item it)
{
assert(L != NULL);
ListNode *new = malloc(sizeof(ListNode));
assert(new != NULL);
new->value = it;
new->next = NULL;
if (L->last == NULL)
L->first = L->last = new;
else {
ListNode *prev, *curr;
prev = NULL; curr = L->first;
while(curr != NULL){
if(curr->value > new->value){
new->next = curr;
if(prev != NULL){
prev->next = new;
}else{
L->first = new;
}
return;
}
}
prev->next = new;
L->last = new;
}
}

// remove item(s)
// assumes no duplicates
void ListDelete(List L, Key k)
{
assert(L != NULL);
ListNode *prev, *curr;
prev = NULL; curr = L->first;
while (curr != NULL) {
if (eq(k,key(curr->value)))
break;
prev = curr;
curr = curr->next;
}
if (curr != NULL) {
if (prev == NULL)
L->first = curr->next;
else
prev->next = curr->next;
free(curr);
if (L->first == NULL)
L->last = NULL;
}
}

// return item with key


Item *ListSearch(List L, Key k)
{
assert(L != NULL);
ListNode *curr = L->first;
while (curr != NULL) {
if (cmp(k,key(curr->value))== 0) {
return &(curr->value);
} else if (less(k,key(curr->value))) {
curr = curr->next;
}else{
return NULL; // key not found
}
}
return NULL;
}

// # items in list
int ListLength(List L)
{
int n = 0;
ListNode *curr = L->first;
while (curr != NULL) {
n++;
curr = curr->next;
}
return n;
}

// C Program to implementation of stack ADT as linked-list

#include<stdio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
//clrscr();
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");
}

// C Program to implementation of Queue ADT as linked-list

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

// A linked list (LL) node to store a queue entry


struct QNode {
int key;
struct QNode* next;
};

// The queue, front stores the front node of LL and rear stores the
// last node of LL
struct Queue {
struct QNode *front, *rear;
};

// A utility function to create a new linked list node.


struct QNode* newNode(int k)
{
struct QNode* temp = (struct QNode*)malloc(sizeof(struct QNode));
temp->key = k;
temp->next = NULL;
return temp;
}

// A utility function to create an empty queue


struct Queue* createQueue()
{
struct Queue* q = (struct Queue*)malloc(sizeof(struct Queue));
q->front = q->rear = NULL;
return q;
}

// The function to add a key k to q


void enQueue(struct Queue* q, int k)
{
// Create a new LL node
struct QNode* temp = newNode(k);

// If queue is empty, then new node is front and rear both


if (q->rear == NULL) {
q->front = q->rear = temp;
return;
}

// Add the new node at the end of queue and change rear
q->rear->next = temp;
q->rear = temp;
}

// Function to remove a key from given queue q


void deQueue(struct Queue* q)
{
// If queue is empty, return NULL.
if (q->front == NULL)
return;

// Store previous front and move front one node ahead


struct QNode* temp = q->front;

q->front = q->front->next;

// If front becomes NULL, then change rear also as NULL


if (q->front == NULL)
q->rear = NULL;

free(temp);
}

// Driver Program to test above functions


int main()
{
struct Queue* q = createQueue();
enQueue(q, 10);
enQueue(q, 20);
deQueue(q);
deQueue(q);
enQueue(q, 30);
enQueue(q, 40);
enQueue(q, 50);
deQueue(q);
printf("Queue Front : %d \n", q->front->key);
printf("Queue Rear : %d", q->rear->key);
return 0;
}

Program 4: Implementation of Binary trees and operations of Binary trees.

#include<stdlib.h>
#include<stdio.h>
struct bin_tree {
int data;
struct bin_tree * right, * left;
};
typedef struct bin_tree node;

void insert(node ** tree, int val)


{
node *temp = NULL;
if(!(*tree))
{
temp = (node *)malloc(sizeof(node));
temp->left = temp->right = NULL;
temp->data = val;
*tree = temp;
return;
}

if(val < (*tree)->data)


{
insert(&(*tree)->left, val);
}
else if(val > (*tree)->data)
{
insert(&(*tree)->right, val);
}

void print_preorder(node * tree)


{
if (tree)
{
printf("%d\n",tree->data);
print_preorder(tree->left);
print_preorder(tree->right);
}

void print_inorder(node * tree)


{
if (tree)
{
print_inorder(tree->left);
printf("%d\n",tree->data);
print_inorder(tree->right);
}
}

void print_postorder(node * tree)


{
if (tree)
{
print_postorder(tree->left);
print_postorder(tree->right);
printf("%d\n",tree->data);
}
}

void deltree(node * tree)


{
if (tree)
{
deltree(tree->left);
deltree(tree->right);
free(tree);
}
}

node* search(node ** tree, int val)


{
if(!(*tree))
{
return NULL;
}

if(val < (*tree)->data)


{
search(&((*tree)->left), val);
}
else if(val > (*tree)->data)
{
search(&((*tree)->right), val);
}
else if(val == (*tree)->data)
{
return *tree;
}
}

void main()
{
node *root;
node *tmp;
//int i;

root = NULL;
/* Inserting nodes into tree */
insert(&root, 9);
insert(&root, 4);
insert(&root, 15);
insert(&root, 6);
insert(&root, 12);
insert(&root, 17);
insert(&root, 2);

/* Printing nodes of tree */


printf("Pre Order Display\n");
print_preorder(root);

printf("In Order Display\n");


print_inorder(root);

printf("Post Order Display\n");


print_postorder(root);

/* Search node into tree */


tmp = search(&root, 4);
if (tmp)
{
printf("Searched node=%d\n", tmp->data);
}
else
{
printf("Data Not found in tree.\n");
}

/* Deleting all nodes of tree */


deltree(root);
}

Program 5: Implementation of Binary Search Trees.


/*
 * C Program to search for an element in a binary search tree
 */
#include <stdio.h>
#include <stdlib.h> 
struct TreeNode {
int data;
struct TreeNode *leftChildNode;
struct TreeNode *rightChildNode;
};
 
typedef struct TreeNode node;
node *rootNode = NULL;
 
/* Function to insert a node in a Binary search tree */
void insertNode(int i, node **n) {
if (*n == NULL) {
(*n) = (node*)malloc(sizeof(node));
(*n)->leftChildNode = NULL;
(*n)->rightChildNode = NULL;
(*n)->data = i;
}
else if ((*n)->data == i)
printf("\nThis value already exists in the tree!");
else if (i > (*n)->data)
insertNode(i, &((*n)->rightChildNode));
else
insertNode(i, &((*n)->leftChildNode));
}
/* End of insertNode() */
 
/* Function to search an element in a Binary search tree */
void searchNode(int i, node **n) {
if (*n == NULL)
printf("\nValue does not exist in tree!");
else if((*n)->data == i)
printf("\nValue found!");
else if(i > (*n)->data)
searchNode(i, &((*n)->rightChildNode));
else
searchNode(i, &((*n)->leftChildNode));
}
/* End of serachNode() */
 
/* The main() program begins */
int main()
{
int ch, num, num1;
do {
printf("\nSelect a choice from the menu below.");
printf("\n1. Insert a node.");
printf("\n2. Search for a node.");
printf("\nChoice: ");
scanf("%d", &ch);
switch(ch) {
case 1:
printf("\nEnter an element: ");
scanf("%d", &num);
insertNode(num, &rootNode);
break;
case 2:
printf("\nEnter the element to be searched for: ");
scanf("%d", &num);
searchNode(num, &rootNode);
break;
default:
exit(0);
}
printf("\nIf you want to return to the menu, press 1.");
printf("\nChoice: ");
scanf("%d", &num);
} while(num == 1);
return 0;
}

Program 6: Implementation of AVL Trees.


// AVL tree implementation in C
#include <stdio.h>
#include <stdlib.h>
// Create Node
struct Node {
int key;
struct Node *left;
struct Node *right;
int height;
};
int max(int a, int b);

// Calculate height
int height(struct Node *N) {
if (N == NULL)
return 0;
return N->height;
}

int max(int a, int b) {


return (a > b) ? a : b;
}

// Create a node
struct Node *newNode(int key) {
struct Node *node = (struct Node *)
malloc(sizeof(struct Node));
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1;
return (node);
}

// Right rotate
struct Node *rightRotate(struct Node *y) {
struct Node *x = y->left;
struct Node *T2 = x->right;

x->right = y;
y->left = T2;

y->height = max(height(y->left), height(y->right)) + 1;


x->height = max(height(x->left), height(x->right)) + 1;

return x;
}

// Left rotate
struct Node *leftRotate(struct Node *x) {
struct Node *y = x->right;
struct Node *T2 = y->left;

y->left = x;
x->right = T2;

x->height = max(height(x->left), height(x->right)) + 1;


y->height = max(height(y->left), height(y->right)) + 1;

return y;
}

// Get the balance factor


int getBalance(struct Node *N) {
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}

// Insert node
struct Node *insertNode(struct Node *node, int key) {
// Find the correct position to insertNode the node and insertNode it
if (node == NULL)
return (newNode(key));

if (key < node->key)


node->left = insertNode(node->left, key);
else if (key > node->key)
node->right = insertNode(node->right, key);
else
return node;

// Update the balance factor of each node and


// Balance the tree
node->height = 1 + max(height(node->left),
height(node->right));

int balance = getBalance(node);


if (balance > 1 && key < node->left->key)
return rightRotate(node);

if (balance < -1 && key > node->right->key)


return leftRotate(node);

if (balance > 1 && key > node->left->key) {


node->left = leftRotate(node->left);
return rightRotate(node);
}

if (balance < -1 && key < node->right->key) {


node->right = rightRotate(node->right);
return leftRotate(node);
}

return node;
}

struct Node *minValueNode(struct Node *node) {


struct Node *current = node;

while (current->left != NULL)


current = current->left;

return current;
}

// Delete a nodes
struct Node *deleteNode(struct Node *root, int key) {
// Find the node and delete it
if (root == NULL)
return root;

if (key < root->key)


root->left = deleteNode(root->left, key);

else if (key > root->key)


root->right = deleteNode(root->right, key);
else {
if ((root->left == NULL) || (root->right == NULL)) {
struct Node *temp = root->left ? root->left : root->right;

if (temp == NULL) {
temp = root;
root = NULL;
} else
*root = *temp;
free(temp);
} else {
struct Node *temp = minValueNode(root->right);

root->key = temp->key;

root->right = deleteNode(root->right, temp->key);


}
}

if (root == NULL)
return root;

// Update the balance factor of each node and


// balance the tree
root->height = 1 + max(height(root->left),
height(root->right));

int balance = getBalance(root);


if (balance > 1 && getBalance(root->left) >= 0)
return rightRotate(root);

if (balance > 1 && getBalance(root->left) < 0) {


root->left = leftRotate(root->left);
return rightRotate(root);
}

if (balance < -1 && getBalance(root->right) <= 0)


return leftRotate(root);

if (balance < -1 && getBalance(root->right) > 0) {


root->right = rightRotate(root->right);
return leftRotate(root);
}

return root;
}

// Print the tree


void printPreOrder(struct Node *root) {
if (root != NULL) {
printf("%d ", root->key);
printPreOrder(root->left);
printPreOrder(root->right);
}
}
int main() {
struct Node *root = NULL;

root = insertNode(root, 2);


root = insertNode(root, 1);
root = insertNode(root, 7);
root = insertNode(root, 4);
root = insertNode(root, 5);
root = insertNode(root, 3);
root = insertNode(root, 8);

printPreOrder(root);

root = deleteNode(root, 3);

printf("\nAfter deletion: ");


printPreOrder(root);

return 0;
}

Program 7: Implementation of Heaps using Priority Queues.

//Priority Queue with heap:

 #include<stdio.h>

#include<malloc.h>

void insert();

void del();

void display();

struct node

int priority;

int info;

struct node *next;

}*start=NULL,*q,*temp,*new;

 
 

typedef struct node N;

int main()

int ch;

clrscr();

do

printf("\n[1] INSERTION\t[2] DELETION\t[3] DISPLAY [4] EXIT\t:");

scanf("%d",&ch);

switch(ch)

case 1:insert();

break;

case 2:del();

break;

case 3:display();

break;

case 4:

break;

while(ch<4);

 
void insert()

int item,itprio;

new=(N*)malloc(sizeof(N));

printf("ENTER THE ELT.TO BE INSERTED :\t");

scanf("%d",&item);

printf("ENTER ITS PRIORITY :\t");

scanf("%d",&itprio);

new->info=item;

new->priority=itprio;

new->next=NULL;

if(start==NULL )

//new->next=start;

start=new;

else if(start!=NULL&&itprio<=start->priority)

{ new->next=start;

start=new;

else

q=start;

while(q->next != NULL && q->next->priority<=itprio)

{q=q->next;}
new->next=q->next;

q->next=new;

void del()

if(start==NULL)

printf("\nQUEUE UNDERFLOW\n");

else

new=start;

printf("\nDELETED ITEM IS %d\n",new->info);

start=start->next;

//free(start);

void display()

temp=start;

if(start==NULL)
printf("QUEUE IS EMPTY\n");

else

printf("QUEUE IS:\n");

if(temp!=NULL)

for(temp=start;temp!=NULL;temp=temp->next)

printf("\n%d priority =%d\n",temp->info,temp->priority);

//temp=temp->next;

Program 8: C program to implement Graph representation.


// A C Program to demonstrate adjacency list
// representation of graphs
#include <stdio.h>
#include <stdlib.h>
 
// A structure to represent an adjacency list node
struct AdjListNode {
    int dest;
    struct AdjListNode* next;
};
 
// A structure to represent an adjacency list
struct AdjList {
    struct AdjListNode* head;
};
 
// A structure to represent a graph. A graph
// is an array of adjacency lists.
// Size of array will be V (number of vertices
// in graph)
struct Graph {
    int V;
    struct AdjList* array;
};
 
// A utility function to create a new adjacency list node
struct AdjListNode* newAdjListNode(int dest)
{
    struct AdjListNode* newNode
        = (struct AdjListNode*)malloc(
            sizeof(struct AdjListNode));
    newNode->dest = dest;
    newNode->next = NULL;
    return newNode;
}
 
// A utility function that creates a graph of V vertices
struct Graph* createGraph(int V)
{
    struct Graph* graph
        = (struct Graph*)malloc(sizeof(struct Graph));
    graph->V = V;
 
    // Create an array of adjacency lists.  Size of
    // array will be V
    graph->array = (struct AdjList*)malloc(
        V * sizeof(struct AdjList));
 
    // Initialize each adjacency list as empty by
    // making head as NULL
    int i;
    for (i = 0; i < V; ++i)
        graph->array[i].head = NULL;
 
    return graph;
}
 
// Adds an edge to an undirected graph
void addEdge(struct Graph* graph, int src, int dest)
{
    // Add an edge from src to dest.  A new node is
    // added to the adjacency list of src.  The node
    // is added at the beginning
    struct AdjListNode* check = NULL;
    struct AdjListNode* newNode = newAdjListNode(dest);
 
    if (graph->array[src].head == NULL) {
        newNode->next = graph->array[src].head;
        graph->array[src].head = newNode;
    }
    else {
 
        check = graph->array[src].head;
        while (check->next != NULL) {
            check = check->next;
        }
        // graph->array[src].head = newNode;
        check->next = newNode;
    }
 
    // Since graph is undirected, add an edge from
    // dest to src also
    newNode = newAdjListNode(src);
    if (graph->array[dest].head == NULL) {
        newNode->next = graph->array[dest].head;
        graph->array[dest].head = newNode;
    }
    else {
        check = graph->array[dest].head;
        while (check->next != NULL) {
            check = check->next;
        }
        check->next = newNode;
    }
 
    // newNode = newAdjListNode(src);
    // newNode->next = graph->array[dest].head;
    // graph->array[dest].head = newNode;
}
 
// A utility function to print the adjacency list
// representation of graph
void printGraph(struct Graph* graph)
{
    int v;
    for (v = 0; v < graph->V; ++v) {
        struct AdjListNode* pCrawl = graph->array[v].head;
        printf("\n Adjacency list of vertex %d\n head ", v);
        while (pCrawl) {
            printf("-> %d", pCrawl->dest);
            pCrawl = pCrawl->next;
        }
        printf("\n");
    }
}
 
// Driver program to test above functions
int main()
{
    // create the graph given in above fugure
    int V = 5;
    struct Graph* graph = createGraph(V);
    addEdge(graph, 0, 1);
    addEdge(graph, 0, 4);
    addEdge(graph, 1, 2);
    addEdge(graph, 1, 3);
    addEdge(graph, 1, 4);
    addEdge(graph, 2, 3);
    addEdge(graph, 3, 4);
 
    // print the adjacency list representation of the above
    // graph
    printGraph(graph);
 
    return 0;
}

Program 9: Given the eight queens puzzle problem of placing eight chess queens on an 8×8 chessboard so that
no two queens attack each other
/* C program to solve N Queen Problem using
   backtracking */
#define N 4
#include <stdbool.h>
#include <stdio.h>
 
/* A utility function to print solution */
void printSolution(int board[N][N])
{
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++)
            printf(" %d ", board[i][j]);
        printf("\n");
    }
}
 
/* A utility function to check if a queen can
   be placed on board[row][col]. Note that this
   function is called when "col" queens are
   already placed in columns from 0 to col -1.
   So we need to check only left side for
   attacking queens */
bool isSafe(int board[N][N], int row, int col)
{
    int i, j;
 
    /* Check this row on left side */
    for (i = 0; i < col; i++)
        if (board[row][i])
            return false;
 
    /* Check upper diagonal on left side */
    for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
        if (board[i][j])
            return false;
 
    /* Check lower diagonal on left side */
    for (i = row, j = col; j >= 0 && i < N; i++, j--)
        if (board[i][j])
            return false;
 
    return true;
}
 
/* A recursive utility function to solve N
   Queen problem */
bool solveNQUtil(int board[N][N], int col)
{
    /* base case: If all queens are placed
      then return true */
    if (col >= N)
        return true;
 
    /* Consider this column and try placing
       this queen in all rows one by one */
    for (int i = 0; i < N; i++) {
        /* Check if the queen can be placed on
          board[i][col] */
        if (isSafe(board, i, col)) {
            /* Place this queen in board[i][col] */
            board[i][col] = 1;
 
            /* recur to place rest of the queens */
            if (solveNQUtil(board, col + 1))
                return true;
 
            /* If placing queen in board[i][col]
               doesn't lead to a solution, then
               remove queen from board[i][col] */
            board[i][col] = 0; // BACKTRACK
        }
    }
 
    /* If the queen cannot be placed in any row in
        this column col  then return false */
    return false;
}
 
/* This function solves the N Queen problem using
   Backtracking. It mainly uses solveNQUtil() to
   solve the problem. It returns false if queens
   cannot be placed, otherwise, return true and
   prints placement of queens in the form of 1s.
   Please note that there may be more than one
   solutions, this function prints one  of the
   feasible solutions.*/
bool solveNQ()
{
    int board[N][N] = { { 0, 0, 0, 0 },
                        { 0, 0, 0, 0 },
                        { 0, 0, 0, 0 },
                        { 0, 0, 0, 0 } };
 
    if (solveNQUtil(board, 0) == false) {
        printf("Solution does not exist");
        return false;
    }
 
    printSolution(board);
    return true;
}
 
// driver program to test above function
int main()
{
    solveNQ();
    return 0;
}
Output: The 1 values indicate placements of queens 
 
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0

Program 10: Given a queue of four elements, the program successfully executed concurrent linked Queues.

#include <stdio.h>
 
#define MAX 50
 
void insert();
void delete();
void display();
int queue_array[MAX];
int rear = - 1;
int front = - 1;
main()
{
int choice;
while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice \n");
} /* End of switch */
} /* End of while */
} /* End of main() */
 
void insert()
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
/*If queue is initially empty */
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item;
}
} /* End of insert() */
 
void delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
} /* End of delete() */
 
void display()
{
int i;
if (front == - 1)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
}
Output:

Enter your choice : 1


Inset the element in queue : 10
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit

Program 11: C program to find out the Maximum flow and Minimum cut in a graph for any given number of
nodes.
#include <stdio.h>
#define WHITE 0
#define GRAY 1
#define BLACK 2
#define MAX_NODES 1000
#define oo 1000000000
int n; // number of nodes
int e; // number of edges
int capacity[MAX_NODES][MAX_NODES]; // capacity matrix
int flow[MAX_NODES][MAX_NODES]; // flow matrix
int color[MAX_NODES]; // needed for breadth-first search
int pred[MAX_NODES]; // array to store augmenting path

int min (int x, int y) {


return x<y ? x : y; // returns minimum of x and y
}
int head,tail;
int q[MAX_NODES+2];

void enqueue (int x) {


q[tail] = x;
tail++;
color[x] = GRAY;
}

int dequeue () {
int x = q[head];
head++;
color[x] = BLACK;
return x;
}
int bfs (int start, int target) {
int u,v;
for (u=0; u<n; u++) {
color[u] = WHITE;
}
head = tail = 0;
enqueue(start);
pred[start] = -1;
while (head!=tail) {
u = dequeue();
// Search all adjacent white nodes v. If the capacity
// from u to v in the residual network is positive,
// enqueue v.
for (v=0; v<n; v++) {
if (color[v]==WHITE && capacity[u][v]-flow[u][v]>0) {
enqueue(v);
pred[v] = u;
}
}
}
// If the color of the target node is black now,
// it means that we reached it.
return color[target]==BLACK;
}
int max_flow (int source, int sink) {
int i,j,u;
// Initialize empty flow.
int max_flow = 0;
for (i=0; i<n; i++) {
for (j=0; j<n; j++) {
flow[i][j] = 0;
}
}
// While there exists an augmenting path,
// increment the flow along this path.
while (bfs(source,sink)) {
// Determine the amount by which we can increment the flow.
int increment = oo;
for (u=n-1; pred[u]>=0; u=pred[u]) {
increment = min(increment,capacity[pred[u]][u]-flow[pred[u]][u]);
}
// Now increment the flow.
for (u=n-1; pred[u]>=0; u=pred[u]) {
flow[pred[u]][u] += increment;
flow[u][pred[u]] -= increment;
}
max_flow += increment;
}
// No augmenting path anymore. We are done.
return max_flow;
}

void read_input_file() {
int a,b,c,i,j;
FILE* input = fopen("data.txt","r");
// read number of nodes and edges
fscanf(input,"%d %d",&n,&e);
printf("\nNumber of Vertices : %d Edges : %d",n,e);
// initialize empty capacity matrix
for (i=0; i<n; i++) {
for (j=0; j<n; j++) {
capacity[i][j] = 0;
}
}
// read edge capacities
for (i=0; i<e; i++) {
fscanf(input,"%d %d %d",&a,&b,&c);
capacity[a][b] = c;
printf("\nA : %d B : %d Capacity : %d",a,b,c);
}
fclose(input);
}

int main () {
read_input_file();
printf("\nPlease enter Source(s) and Sink(t) :\n");
int s=0,t=n-1;
scanf("%d %d",&s,&t);
printf("\nMax Flow : %d\n",max_flow(s,t));
return 0;
}

Output:

You might also like