0% found this document useful (0 votes)
20 views61 pages

Program - All Units

Uploaded by

purushothsatha
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)
20 views61 pages

Program - All Units

Uploaded by

purushothsatha
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/ 61

S11BLH31 DATA STRUCTURES USING C

UNIT - 1

1. Implementation of Singly Linked List (Creating a List and Display)

1.a. Singly Linked List

#include <stdio.h>
#include <stdlib.h>
// Creation of node for linked list
struct node
{
int data; //Data of the node
struct node *next; //Address of the next node
}*newnode;
// Creating function for various operations
void createNodeList(int n); // function to create the list
void displayList(); // function to display the list
int main()
{
int n;
printf("\n\n Linked List : To create and display Singly Linked List :\n");
printf("-------------------------------------------------------------\n");
printf(" Input the number of nodes : ");
scanf("%d", &n);
createNodeList(n); // Calling a Function to create a list
printf("\n Data entered in the list : \n");
displayList(); // Calling a function to display the created list
return 0;

Page | 1
}
void createNodeList(int n)
{
struct node *fnNode, *tmp;
int data, i;
newnode = (struct node *)malloc(sizeof(struct node));
if(newnode == NULL) //check whether the fnnode is NULL and if so no memory allocation
{
printf(" Memory can not be allocated.");
}
else
{
// reads data for the node through keyboard
printf(" Input data for node 1 : ");
scanf("%d", &data);
newnode->data = data;
newnode->next = NULL; // links the address field to NULL
tmp = newnode;
// Creating n nodes and adding to linked list
for(i=2; i<=n; i++)
{
fnNode = (struct node *)malloc(sizeof(struct node));
if(fnNode == NULL)
{
printf(" Memory can not be allocated.");
break;
}

Page | 2
else
{
printf(" Input data for node %d : ", i);
scanf(" %d", &data);

fnNode->data= data; // links the num field of fnNode with num

fnNode->next = NULL; // links the address field of fnNode with NULL


tmp->next = fnNode; // links previous node i.e. tmp to the fnNode
tmp = tmp->next;
}
}
}
}
void displayList()
{
struct node *tmp;
if(newnode == NULL)
{
printf(" List is empty.");
}
else
{
tmp = newnode;
while(tmp != NULL)
{
printf(" Data = %d\n", tmp->data); // prints the data of current node

tmp = tmp->next; // increments the position of current node

Page | 3
}
}
}
Ouput

1.b. Doubly Linked List


// implementation of double linked list
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node * next;
struct node * prev;
}*head,*newnode, *temp;
void create(); // function to create the list
void display(); // function to display the list
int main()
{

Page | 4
int n;
printf("\n\n Linked List : To create and display Double Linked List :\n");
printf("-------------------------------------------------------------\n");
create(); // Calling a Function to create a list
printf("\n Data entered in the list : \n");
display(); // Calling a function to display the created list
return 0;
}

void create()
{
head = 0;
int choice,data;
while(choice)
{
newnode = (struct node*)malloc(sizeof(struct node));
printf("enter data");
scanf("%d",&data);
newnode->data = data;
newnode->next = 0;
newnode->prev = 0;
if(head==0)
{
head = temp = newnode;
}
else
{

Page | 5
temp->next = newnode;
newnode->prev = temp;
}
printf("do you want to continue- enter 1 to continue");
scanf("%d",&choice);
}
//free(temp);
}
void display()
{
temp = head;
while(temp!=NULL)
{
printf("%d",temp->data);
temp = temp->next;
}
}
Ouput

Page | 6
1.c. Circular Linked List
// implementation of Circular linked list
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node * next;
}*head,*newnode,*temp;
void create();
void display();
int main()
{
//int n;
printf("\n\n Linked List : To create and display Circular Linked List :\n");
printf("-------------------------------------------------------------\n");
create(); // Calling a Function to create a list
printf("\n Data entered in the list : \n");
display(); // Calling a function to display the created list
return 0;
}

void create()
{
head=0;
int choice;
while(choice)

Page | 7
{
newnode = (struct node *)malloc(sizeof(struct node));
printf(" Enter data : ");
scanf("%d", &newnode->data);
newnode->next=0;
if(head==0)
{
head=temp=newnode;
}
else
{
temp->next=newnode;
temp=newnode;
temp->next=head;
}
printf("Enter 1 to continue");
scanf("%d", &choice);
}
}

void display()
{
temp = head;
while(temp->next!=head)
{
printf("%d",temp->data);
temp = temp->next;

Page | 8
}
}
Ouput

1.d. Circularly Double Linked List


// implementation of Circularly Double linked list
// implementation of double linked list
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node * next;
struct node * prev;
}*head,*newnode, *temp;
void create(); // function to create the list
void display(); // function to display the list
int main()
{
int n;
printf("\n\n Linked List : To create and display Circular Double Linked List
:\n");

Page | 9
printf("-------------------------------------------------------------\n");
create(); // Calling a Function to create a list
printf("\n Data entered in the list : \n");
display(); // Calling a function to display the created list
return 0;
}

void create()
{
head = 0;
int choice,data;
while(choice)
{
newnode = (struct node*)malloc(sizeof(struct node));
printf("enter data");
scanf("%d",&data);
newnode->data = data;
newnode->next = 0;
newnode->prev = 0;
if(head==0)
{
head = temp = newnode;
}
else
{
temp->next = newnode;
newnode->prev = temp;

Page | 10
}
printf("do you want to continue- enter 1 to continue");
scanf("%d",&choice);
}
//free(temp);
}
void display()
{
temp = head;
while(temp->next!=head)
{
printf("%d",temp->data);
temp = temp->next;
}
printf("\t");
printf("%d",temp->data);
}
Ouput

Page | 11
INSERT AN ELEMENT IN LINKED LIST

2.A. Singly Linked List

#include <stdio.h>
#include <stdlib.h>
// Creation of node for linked list
struct node
{
int data; //Data of the node
struct node *next; //Address of the next node
}*newnode;
// Creating function for various operations
void createNodeList(int n); // function to create the list
void NodeInsertatEnd(int data); // function to insert at end
void NodeInsertatBegin(int data); // function to insert at beginning
void insertNodeAtMiddle(int data, int pos); // function to insert in the middle
void displayList(); // function to display the list

int main()
{
int n,data,pos;
printf("\n\n Linked List : To create and display Singly Linked List :\n");
printf("-------------------------------------------------------------\n");
printf(" Input the number of nodes : ");
scanf("%d", &n);
createNodeList(n); // Calling a Function to create a list
printf("\n Data entered in the list : \n");
displayList(); // Calling a function to display the created list
printf(" Input the number to be inserted : ");
scanf("%d", &data);
NodeInsertatEnd(data); // Calling a function to insert at END
printf("\n Data entered in the list after insert: \n");
displayList(); // Calling a function to display the created list after insert
printf(" Input the number to be inserted : ");
scanf("%d", &data);
NodeInsertatBegin(data); // Calling a function to insert at BEGINING
printf("\n Data entered in the list after insert: \n");
displayList(); // Calling a function to display the created list after insert
printf(" Input the number to be inserted : ");
scanf("%d%d", &data,&pos);
insertNodeAtMiddle(data,pos); // Calling a function to insert at given POSITION

Page | 12
printf("\n Data entered in the list after insert: \n");
displayList(); // Calling a function to display the created list after insert
return 0;
}
void createNodeList(int n)
{
struct node *fnNode, *tmp;
int data, i;
newnode = (struct node *)malloc(sizeof(struct node));
if(newnode == NULL) //check whether the fnnode is NULL and if so no memory allocation
{
printf(" Memory can not be allocated.");
}
else
{
// reads data for the node through keyboard
printf(" Input data for node 1 : ");
scanf("%d", &data);
newnode->data = data;
newnode->next = NULL; // links the address field to NULL
tmp = newnode;
// Creating n nodes and adding to linked list
for(i=2; i<=n; i++)
{
fnNode = (struct node *)malloc(sizeof(struct node));
if(fnNode == NULL)
{
printf(" Memory can not be allocated.");
break;
}
else
{
printf(" Input data for node %d : ", i);
scanf(" %d", &data);

fnNode->data= data; // links the num field of fnNode with num


fnNode->next = NULL; // links the address field of fnNode with NULL
tmp->next = fnNode; // links previous node i.e. tmp to the fnNode
tmp = tmp->next;
}
}
}

Page | 13
}
void NodeInsertatEnd(int data)
{
struct node *fnNode, *tmp;
fnNode = (struct node*)malloc(sizeof(struct node));
if(fnNode == NULL)
{
printf(" Memory can not be allocated.");
}
else
{
printf(" Input data for insert : ");
scanf("%d", &data);
fnNode->data = data; //Links the data part
fnNode->next = NULL;
tmp = newnode;
while(tmp->next != NULL)
tmp = tmp->next;
tmp->next = fnNode; //Links the address part
}
}

void NodeInsertatBegin(int data)


{
struct node *fnNode;
fnNode = (struct node*)malloc(sizeof(struct node));
if(fnNode == NULL)
{
printf(" Memory can not be allocated.");
}
else
{
printf(" Input data for insert : ");
scanf("%d", &data);
fnNode->data = data; //Links the data part
fnNode->next = newnode; //Links the address part
newnode = fnNode; //Makes stnode as first node
}
}

Page | 14
void insertNodeAtMiddle(int data, int pos)
{
int i;
struct node *fnNode, *tmp;
fnNode = (struct node*)malloc(sizeof(struct node));
if(fnNode == NULL)
{
printf(" Memory can not be allocated.");
}
else
{
printf(" Input data for insert : ");
scanf("%d", &data);
fnNode->data = data; //Links the data part
fnNode->next = NULL;
tmp = newnode;
for(i=2; i<=pos-1; i++)
{
tmp = tmp->next;

if(tmp == NULL)
break;
}
if(tmp != NULL)
{
fnNode->next = tmp->next; //Links the address part of new node
tmp->next = fnNode;
}
else
{
printf(" Insert is not possible to the given position.\n");
}
}
}

void displayList()
{
struct node *tmp;
if(newnode == NULL)
{
printf(" List is empty.");
}

Page | 15
else
{
tmp = newnode;
while(tmp != NULL)
{
printf(" Data = %d\n", tmp->data); // prints the data of current node
tmp = tmp->next; // increments the position of current node
}
}
}

2.B. Circular Linked List

#include <stdio.h>
#include <stdlib.h>
// Creation of node for linked list
struct node
{
int data; //Data of the node
struct node *next; //Address of the next node
}*newnode;
// Creating function for various operations
void createNodeList(int n); // function to create the list
void NodeInsertatEnd(int data); // function to insert at end
void NodeInsertatBegin(int data); // function to insert at beginning
void insertNodeAtMiddle(int data, int pos); // function to insert in the middle
void displayList(); // function to display the list

int main()
{
int n,data,pos;
printf("\n\n Linked List : To create and display Singly Linked List :\n");
printf("-------------------------------------------------------------\n");
printf(" Input the number of nodes : ");
scanf("%d", &n);
createNodeList(n); // Calling a Function to create a list
printf("\n Data entered in the list : \n");
displayList(); // Calling a function to display the created list
printf(" Input the number to be inserted : ");
scanf("%d", &data);
NodeInsertatEnd(data); // Calling a function to insert at END

Page | 16
printf("\n Data entered in the list after insert: \n");
displayList(); // Calling a function to display the created list after insert
printf(" Input the number to be inserted : ");
scanf("%d", &data);
NodeInsertatBegin(data); // Calling a function to insert at BEGINING
printf("\n Data entered in the list after insert: \n");
displayList(); // Calling a function to display the created list after insert
printf(" Input the number to be inserted : ");
scanf("%d%d", &data,&pos);
insertNodeAtMiddle(data,pos); // Calling a function to insert at given POSITION
printf("\n Data entered in the list after insert: \n");
displayList(); // Calling a function to display the created list after insert
return 0;
}
void createNodeList(int n)
{
struct node *fnNode, *tmp;
int data, i;
newnode = (struct node *)malloc(sizeof(struct node));
if(newnode == NULL) //check whether the fnnode is NULL and if so no memory allocation
{
printf(" Memory can not be allocated.");
}
else
{
// reads data for the node through keyboard
printf(" Input data for node 1 : ");
scanf("%d", &data);
newnode->data = data;
newnode->next = head; // links the address field to head
tmp = newnode;
// Creating n nodes and adding to linked list
for(i=2; i<=n; i++)
{
fnNode = (struct node *)malloc(sizeof(struct node));
if(fnNode == NULL)
{
printf(" Memory can not be allocated.");
break;
}
else
{

Page | 17
printf(" Input data for node %d : ", i);
scanf(" %d", &data);

fnNode->data= data; // links the num field of fnNode with num


fnNode->next = NULL; // links the address field of fnNode with NULL
tmp->next = fnNode; // links previous node i.e. tmp to the fnNode
tmp = tmp->next;
}
}
}
}
void NodeInsertatEnd(int data)
{
struct node *fnNode, *tmp;
fnNode = (struct node*)malloc(sizeof(struct node));
if(fnNode == NULL)
{
printf(" Memory can not be allocated.");
}
else
{
printf(" Input data for insert : ");
scanf("%d", &data);
fnNode->data = data; //Links the data part
fnNode->next = NULL;
tmp = newnode;
while(tmp->next != head)
tmp = tmp->next;
tmp->next = fnNode; //Links the address part
}
}

void NodeInsertatBegin(int data)


{
struct node *fnNode;
fnNode = (struct node*)malloc(sizeof(struct node));
if(fnNode == NULL)
{
printf(" Memory can not be allocated.");
}
else

Page | 18
{
printf(" Input data for insert : ");
scanf("%d", &data);
fnNode->data = data; //Links the data part
fnNode->next = newnode; //Links the address part
newnode = fnNode; //Makes stnode as first node
}
}
void insertNodeAtMiddle(int data, int pos)
{
int i;
struct node *fnNode, *tmp;
fnNode = (struct node*)malloc(sizeof(struct node));
if(fnNode == NULL)
{
printf(" Memory can not be allocated.");
}
else
{
printf(" Input data for insert : ");
scanf("%d", &data);
fnNode->data = data; //Links the data part
fnNode->next = NULL;
tmp = newnode;
for(i=2; i<=pos-1; i++)
{
tmp = tmp->next;
if(tmp == NULL)
break;
}
if(tmp != NULL)
{
fnNode->next = tmp->next; //Links the address part of new node
tmp->next = fnNode;
}
else
{
printf(" Insert is not possible to the given position.\n");
}
}
}

Page | 19
void displayList()
{
struct node *tmp;
if(newnode == NULL)
{
printf(" List is empty.");
}
else
{
tmp = newnode;
while(tmp->next != head)
{
printf(" Data = %d\n", tmp->data); // prints the data of current node
tmp = tmp->next; // increments the position of current node
}
}
}

2.C. Double Linked List and 2.D. Circularly Double Linked List

Insert at beginning

// insert node at the front


void insertFront(struct Node** head, int data) {
// allocate memory for newNode
struct Node* newNode = new Node;
// assign data to newNode
newNode->data = data;
// point next of newNode to the first node of the doubly linked list
newNode->next = (*head);
// point prev to NULL
newNode->prev = NULL;

// point previous of the first node (now first node is the second node) to
newNode

Page | 20
if ((*head) != NULL)
(*head)->prev = newNode;
// head points to newNode
(*head) = newNode;
}
Insert at a given position

// insert a node after a specific node (middle)


void insertAfter(struct Node* prev_node, int data) {

// check if previous node is NULL


if (prev_node == NULL) {
cout << "previous node cannot be NULL";
return;
}

// allocate memory for newNode


struct Node* newNode = new Node;

// assign data to newNode


newNode->data = data;

// set next of newNode to next of prev node


newNode->next = prev_node->next;

// set next of prev node to newNode


prev_node->next = newNode;

// set prev of newNode to the previous node

Page | 21
newNode->prev = prev_node;

// set prev of newNode's next to newNode


if (newNode->next != NULL)
newNode->next->prev = newNode;
}

Insert at End

// insert a newNode at the end of the list


void insertEnd(struct Node** head, int data) {
// allocate memory for node
struct Node* newNode = new Node;

// assign data to newNode


newNode->data = data;

// assign NULL to next of newNode


newNode->next = NULL;

// store the head node temporarily (for later use)


struct Node* temp = *head;

// if the linked list is empty, make the newNode as head node


if (*head == NULL) {
newNode->prev = NULL;
*head = newNode;
return;
}

Page | 22
// if the linked list is not empty, traverse to the end of the linked list
while (temp->next != NULL)
temp = temp->next;

// now, the last node of the linked list is temp

// point the next of the last node (temp) to newNode.


temp->next = newNode;

// assign prev of newNode to temp


newNode->prev = temp;
}
DELETE AN ELEMENT IN LINKED LIST

3.A. Singly Linked List

#include <stdio.h>
#include <stdlib.h>
// Creation of node for linked list
struct node
{
int data; //Data of the node
struct node *next; //Address of the next node
}*newnode, *tmp,*head,*prevnode;
// Creating function for various operations
void createNodeList(int n); // function to create the list
void deleteend(); // function to delete at end
void deletegivenpos(); // function to delete in the middle
void displayList(); // function to display the list

int main()
{
int n,data,pos;
printf("\n\n Linked List : To create and display Singly Linked List :\n");
printf("-------------------------------------------------------------\n");

Page | 23
printf(" Input the number of nodes : ");
scanf("%d", &n);
createNodeList(n); // Calling a Function to create a list
printf("\n Data entered in the list : \n");
displayList(); // Calling a function to display the created list
//printf(" Input the number to be deleted : ");
//scanf("%d", &data);
deleteend(); // Calling a function to delete at END
printf("\n Data entered in the list after delete: \n");
displayList(); // Calling a function to display the created list after delete
deletegivenpos(); // Calling a function to delete at given POSITION
printf("\n Data entered in the list after delete: \n");
displayList(); // Calling a function to display the created list after delete
return 0;
}

void createNodeList(int n)
{
struct node *fnNode, *tmp;
int data, i;
newnode = (struct node *)malloc(sizeof(struct node));
if(newnode == NULL) //check whether the fnnode is NULL and if so no memory
allocation
{
printf(" Memory can not be allocated.");
}
else
{
// reads data for the node through keyboard
printf(" Input data for node 1 : ");
scanf("%d", &data);
newnode->data = data;
newnode->next = head; // links the address field to head
tmp = newnode;
// Creating n nodes and adding to linked list
for(i=2; i<=n; i++)
{
fnNode = (struct node *)malloc(sizeof(struct node));
if(fnNode == NULL)
{
printf(" Memory can not be allocated.");
break;

Page | 24
}
else
{
printf(" Input data for node %d : ", i);
scanf(" %d", &data);

fnNode->data= data; // links the num field of fnNode with num


fnNode->next = NULL; // links the address field of fnNode with NULL
tmp->next = fnNode; // links previous node i.e. tmp to the fnNode
tmp = tmp->next;
}
}
}
}

void deleteend()
{
struct node*prevnode;
tmp = head;
while(tmp->next!=0)
{
prevnode = tmp;
tmp = tmp->next;
if(tmp == head)
{
tmp = 0;
free(tmp);
}
else
{
prevnode->next = 0;
free(tmp);
}
}
}
void deletegivenpos()
{
struct node*nextnode;
int pos,i=1;
tmp = head;
printf("enter the position");

Page | 25
scanf("%d",&pos);
while(i<pos-1)
{
tmp = tmp->next;
i++;
}
nextnode = tmp->next;
tmp->next = nextnode->next;
free(nextnode);
}
void displayList()
{
struct node *tmp;
if(newnode == NULL)
{
printf(" List is empty.");
}
else
{
tmp = newnode;
while(tmp->next != 0)
{
printf(" Data = %d\n", tmp->data); // prints the data of current node
tmp = tmp->next; // increments the position of current node
}
}
//printf("\t");
printf(" Data = %d\n", tmp->data);
}

3.B. Circular Linked List

#include <stdio.h>
#include <stdlib.h>
// Creation of node for linked list
struct node
{
int data; //Data of the node
struct node *next; //Address of the next node
}*newnode, *tmp,*head,*prevnode;
// Creating function for various operations
void createNodeList(int n); // function to create the list

Page | 26
void deleteend(); // function to delete at end
void deletegivenpos(); // function to delete in the middle
void displayList(); // function to display the list

int main()
{
int n,data,pos;
printf("\n\n Linked List : To create and display Singly Linked List :\n");
printf("-------------------------------------------------------------\n");
printf(" Input the number of nodes : ");
scanf("%d", &n);
createNodeList(n); // Calling a Function to create a list
printf("\n Data entered in the list : \n");
displayList(); // Calling a function to display the created list
//printf(" Input the number to be deleted : ");
//scanf("%d", &data);
deleteend(); // Calling a function to delete at END
printf("\n Data entered in the list after delete: \n");
displayList(); // Calling a function to display the created list after delete
deletegivenpos(); // Calling a function to delete at given POSITION
printf("\n Data entered in the list after delete: \n");
displayList(); // Calling a function to display the created list after delete
return 0;
}

void createNodeList(int n)
{
struct node *fnNode, *tmp;
int data, i;
newnode = (struct node *)malloc(sizeof(struct node));
if(newnode == NULL) //check whether the fnnode is NULL and if so no memory
allocation
{
printf(" Memory can not be allocated.");
}
else
{
// reads data for the node through keyboard
printf(" Input data for node 1 : ");
scanf("%d", &data);
newnode->data = data;
newnode->next = head; // links the address field to head

Page | 27
tmp = newnode;
// Creating n nodes and adding to linked list
for(i=2; i<=n; i++)
{
fnNode = (struct node *)malloc(sizeof(struct node));
if(fnNode == NULL)
{
printf(" Memory can not be allocated.");
break;
}
else
{
printf(" Input data for node %d : ", i);
scanf(" %d", &data);

fnNode->data= data; // links the num field of fnNode with num


fnNode->next = head; // links the address field of fnNode with NULL
tmp->next = fnNode; // links previous node i.e. tmp to the fnNode
tmp = tmp->next;
}
}
}
}

void deleteend()
{
struct node*prevnode;
tmp = head;
while(tmp->next!=0)
{
prevnode = tmp;
tmp = tmp->next;
if(tmp == head)
{
tmp = 0;
free(tmp);
}
else
{
prevnode->next = 0;
free(tmp);

Page | 28
}
}
}
void deletegivenpos()
{
struct node*nextnode;
int pos,i=1;
tmp = head;
printf("enter the position");
scanf("%d",&pos);
while(i<pos-1)
{
tmp = tmp->next;
i++;
}
nextnode = tmp->next;
tmp->next = nextnode->next;
free(nextnode);
}
void displayList()
{
struct node *tmp;
if(newnode == NULL)
{
printf(" List is empty.");
}
else
{
tmp = newnode;
while(tmp->next != head)
{
printf(" Data = %d\n", tmp->data); // prints the data of current node
tmp = tmp->next; // increments the position of current node
}
}
//printf("\t");
printf(" Data = %d\n", tmp->data);
}

Page | 29
3.C. Double Linked List and 3.D. Circularly Double Linked List

Page | 30
// C program to implement
// the above approach
#include <stdio.h>
#include <stdlib.h>

// A node of the doubly linked list


struct Node
{
int data;
struct Node* next;
struct Node* prev;
};

/* Function to delete a node in a Doubly


Linked List. head_ref --> pointer to
head node pointer. del --> pointer
to node to be deleted. */
void deleteNode(struct Node** head_ref,
struct Node* del)
{
// Base case
if (*head_ref == NULL || del == NULL)
return;

// If node to be deleted is head node


if (*head_ref == del)
*head_ref = del->next;

Page | 31
/* Change next only if node to be deleted
is NOT the last node */
if (del->next != NULL)
del->next->prev = del->prev;

/* Change prev only if node to be deleted


is NOT the first node */
if (del->prev != NULL)
del->prev->next = del->next;

// Finally, free the memory occupied by del


free(del);
return;
}

// UTILITY FUNCTIONS
/* Function to insert a node at the
beginning of the Doubly Linked List */
void push(struct Node** head_ref,
int new_data)
{
// Allocate node
struct Node* new_node =
(struct Node*)malloc(sizeof(struct Node));

// Put in the data

Page | 32
new_node->data = new_data;

/* Since we are adding at the beginning,


prev is always NULL */
new_node->prev = NULL;
// Link the old list of the new node
new_node->next = (*head_ref);
// Change prev of head node to new node
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
// Move the head to point to the new node
(*head_ref) = new_node;
}
/* Function to print nodes in a given doubly
linked list. This function is same as
printList() of singly linked list */
void printList(struct Node* node)
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
}
// Driver code
int main()
{

Page | 33
// Start with the empty list
struct Node* head = NULL;
/* Let us create the doubly
linked list 10<->8<->4<->2 */
push(&head, 2);
push(&head, 4);
push(&head, 8);
push(&head, 10);
printf(
"Original Linked list ");
printList(head);
/* Delete nodes from the doubly
linked list */
// Delete first node
deleteNode(&head, head);
// Delete middle node
deleteNode(&head, head->next);
// Delete last node
deleteNode(&head, head->next);
/* Modified linked list will be
NULL<-8->NULL */
printf(
"Modified Linked list ");
printList(head);
getchar();
}

Page | 34
UNIT 2
IMPLEMENTATION OF STACKS USING ARRAYS

#include<stdio.h>
#include<stdlib.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:
{

Page | 35
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()
{

Page | 36
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");
}
}

Page | 37
UNIT 3
IMPLEMENTATION OF QUEUES USING ARRAYS

// Queue implementation in C using ARRAYS


#include <stdio.h>
#define SIZE 5
void enQueue(int);
void deQueue();
void display();
int items[SIZE], front = -1, rear = -1;
int main() {
//deQueue is not possible on empty queue
deQueue();
//enQueue 5 elements
enQueue(1);
enQueue(2);
enQueue(3);
enQueue(4);
enQueue(5);
// 6th element can't be added to because the queue is full
enQueue(6);
display();
//deQueue removes element entered first i.e. 1
deQueue();
//Now we have just 4 elements
display();
return 0;
}
void enQueue(int value) {
if (rear == SIZE - 1)
printf("\nQueue is Full!!");
else {
if (front == -1)
front = 0;
rear++;
items[rear] = value;
printf("\nInserted -> %d", value);
}
}
void deQueue() {
if (front == -1)
printf("\nQueue is Empty!!");
else {
printf("\nDeleted : %d", items[front]);
front++;
if (front > rear)
front = rear = -1;
}
Page | 38
}
// Function to print the queue
void display() {
if (rear == -1)
printf("\nQueue is Empty!!!");
else {
int i;
printf("\nQueue elements are:\n");
for (i = front; i <= rear; i++)
printf("%d ", items[i]);
}
printf("\n");
}

SEARCHING TECHNIQUES
LINEAR SERACH
#include <stdio.h>
int main()
{
int array[100], search, c, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter a number to search\n");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);
return 0;
}

BINARY SEARCH

#include <stdio.h>
int iterativeBinarySearch(int array[], int start_index, int end_index, int element){
while (start_index<= end_index){
int middle = start_index + (end_index- start_index )/2;
if (array[middle] == element)

Page | 39
return middle;
if (array[middle] < element)
start_index = middle + 1;
else
end_index = middle - 1;
}
return -1;
}
int main(void){
int array[] = {1, 4, 7, 9, 16, 56, 70};
int n = 7;
int element = 16;
int found_index = iterativeBinarySearch(array, 0, n-1, element);
if(found_index == -1 ) {
printf("Element not found in the array ");
}
else {
printf("Element found at index : %d",found_index);
}
return 0;
}

SORTING TECHNIQUES
a) Bubble sort:
// C program for implementation of Bubble sort
#include <stdio.h>

void swap(int *xp, int *yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

// A function to implement bubble sort


void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i< n-1; i++)

Page | 40
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
if (arr[j] >arr[j+1])
swap(&arr[j], &arr[j+1]);
}

/* Function to print an array */


void printArray(int arr[], int size)
{
int i;
for (i=0; i< size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Driver program to test above functions


int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
b) Insertion sort:
// C program for insertion sort
#include <math.h>
#include <stdio.h>

/* Function to sort an array using insertion sort*/


void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i< n; i++) {
key = arr[i];
j = i - 1;

/* Move elements of arr[0..i-1], that are


greater than key, to one position ahead
of their current position */
while (j >= 0 &&arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

// A utility function to print an array of size n

Page | 41
void printArray(int arr[], int n)
{
int i;
for (i = 0; i< n; i++)
printf("%d ", arr[i]);
printf("\n");
}

/* Driver program to test insertion sort */


int main()
{
int arr[] = { 12, 11, 13, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);

insertionSort(arr, n);
printArray(arr, n);

return 0;
}
-----------------------------------------------------------------------------------------------------------
c) Selection Sort:
// C program for implementation of selection sort
#include <stdio.h>

void swap(int *xp, int *yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void selectionSort(int arr[], int n)


{
int i, j, min_idx;

// One by one move boundary of unsorted subarray


for (i = 0; i< n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] <arr[min_idx])
min_idx = j;

// Swap the found minimum element with the first element


swap(&arr[min_idx], &arr[i]);
}
}

/* Function to print an array */

Page | 42
void printArray(int arr[], int size)
{
int i;
for (i=0; i< size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Driver program to test above functions


int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
------------------------------------------------------------------------------------------------------
d) Heap sort:
#include<stdio.h>
int temp;

void heapify(int arr[], int size, int i)


{
int largest = i;
int left = 2*i + 1;
int right = 2*i + 2;

if (left < size &&arr[left] >arr[largest])


largest = left;

if (right < size &&arr[right] >arr[largest])


largest = right;

if (largest != i)
{
temp = arr[i];
arr[i]= arr[largest];
arr[largest] = temp;
heapify(arr, size, largest);
}
}

void heapSort(int arr[], int size)


{
int i;
for (i = size / 2 - 1; i>= 0; i--)
heapify(arr, size, i);
for (i=size-1; i>=0; i--)

Page | 43
{
temp = arr[0];
arr[0]= arr[i];
arr[i] = temp;
heapify(arr, i, 0);
}
}

void main()
{
int arr[] = {1, 10, 2, 3, 4, 1, 2, 100,23, 2};
int i;
int size = sizeof(arr)/sizeof(arr[0]);

heapSort(arr, size);

printf("printing sorted elements\n");


for (i=0; i<size; ++i)
printf("%d\n",arr[i]);
}
e) Shell sort:
/*
* C Program to sort an array using Shell Sort technique
*/
#include <stdio.h>
void shellsort(int arr[], int num)
{
int i, j, k, tmp;
for (i = num / 2; i> 0; i = i / 2)
{
for (j = i; j < num; j++)
{
for(k = j - i; k >= 0; k = k - i)
{
if (arr[k+i] >= arr[k])
break;
else
{
tmp = arr[k];
arr[k] = arr[k+i];
arr[k+i] = tmp;
}
}
}
}
}
int main()
{
int arr[30];
int k, num;

Page | 44
printf("Enter total no. of elements : ");
scanf("%d", &num);
printf("\nEnter %d numbers: ", num);

for (k = 0 ; k < num; k++)


{
scanf("%d", &arr[k]);
}
shellsort(arr, num);
printf("\n Sorted array is: ");
for (k = 0; k < num; k++)
printf("%d ", arr[k]);
return 0;
}
f) Quick sort:
/*
* C Program to Perform Quick Sort on a set of Entries from a File
* using Recursion
*/
#include <stdio.h>

void quicksort (int [], int, int);

int main()
{
int list[50];
int size, i;

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


scanf("%d", &size);
printf("Enter the elements to be sorted:\n");
for (i = 0; i< size; i++)
{
scanf("%d", &list[i]);
}
quicksort(list, 0, size - 1);
printf("After applying quick sort\n");
for (i = 0; i< size; i++)
{
printf("%d ", list[i]);
}
printf("\n");

return 0;
}
void quicksort(int list[], int low, int high)
{
int pivot, i, j, temp;
if (low < high)
{

Page | 45
pivot = low;
i = low;
j = high;
while (i< j)
{
while (list[i] <= list[pivot] &&i<= high)
{
i++;
}
while (list[j] > list[pivot] && j >= low)
{
j--;
}
if (i< j)
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
temp = list[j];
list[j] = list[pivot];
list[pivot] = temp;
quicksort(list, low, j - 1);
quicksort(list, j + 1, high);
}
}
g) Merge sort:
#include <stdio.h>
#define max 10
int a[11] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 };
int b[10];
void merging(int low, int mid, int high) {
int l1, l2, i;
for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) {
if(a[l1] <= a[l2])
b[i] = a[l1++];
else
b[i] = a[l2++];
}
while(l1 <= mid)
b[i++] = a[l1++];

while(l2 <= high)


b[i++] = a[l2++];
for(i = low; i<= high; i++)
a[i] = b[i];
}
void sort(int low, int high) {
int mid;

Page | 46
if(low < high) {
mid = (low + high) / 2;
sort(low, mid);
sort(mid+1, high);
merging(low, mid, high);
} else {
return;
}
}
int main() {
int i;

printf("List before sorting\n");


for(i = 0; i<= max; i++)
printf("%d ", a[i]);
sort(0, max);
printf("\nList after sorting\n");
for(i = 0; i<= max; i++)
printf("%d ", a[i]);
}

Page | 47
UNIT 4
BINARY SEARCH TREE

// C program to implement binary search tree


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

// Define a structure for a binary tree node


struct BinaryTreeNode {
int key;
struct BinaryTreeNode *left, *right;
};

// Function to create a new node with a given value


struct BinaryTreeNode* newNodeCreate(int value)
{
struct BinaryTreeNode* temp
= (struct BinaryTreeNode*)malloc(
sizeof(struct BinaryTreeNode));
temp->key = value;
temp->left = temp->right = NULL;
return temp;
}

// Function to search for a node with a specific key in the


// tree
struct BinaryTreeNode*
searchNode(struct BinaryTreeNode* root, int target)
{
if (root == NULL || root->key == target) {
return root;
}
if (root->key < target) {
return searchNode(root->right, target);
}
return searchNode(root->left, target);
}

// Function to insert a node with a specific value in the


// tree
struct BinaryTreeNode*
insertNode(struct BinaryTreeNode* node, int value)
{
if (node == NULL) {
return newNodeCreate(value);
}
if (value < node->key) {
node->left = insertNode(node->left, value);
}

Page | 48
else if (value > node->key) {
node->right = insertNode(node->right, value);
}
return node;
}

// Function to perform post-order traversal


void postOrder(struct BinaryTreeNode* root)
{
if (root != NULL) {
postOrder(root->left);
postOrder(root->right);
printf(" %d ", root->key);
}
}

// Function to perform in-order traversal


void inOrder(struct BinaryTreeNode* root)
{
if (root != NULL) {
inOrder(root->left);
printf(" %d ", root->key);
inOrder(root->right);
}
}

// Function to perform pre-order traversal


void preOrder(struct BinaryTreeNode* root)
{
if (root != NULL) {
printf(" %d ", root->key);
preOrder(root->left);
preOrder(root->right);
}
}

// Function to find the minimum value


struct BinaryTreeNode* findMin(struct BinaryTreeNode* root)
{
if (root == NULL) {
return NULL;
}
else if (root->left != NULL) {
return findMin(root->left);
}
return root;
}

// Function to delete a node from the tree


struct BinaryTreeNode* delete (struct BinaryTreeNode* root,

Page | 49
int x)
{
if (root == NULL)
return NULL;

if (x > root->key) {
root->right = delete (root->right, x);
}
else if (x < root->key) {
root->left = delete (root->left, x);
}
else {
if (root->left == NULL && root->right == NULL) {
free(root);
return NULL;
}
else if (root->left == NULL
|| root->right == NULL) {
struct BinaryTreeNode* temp;
if (root->left == NULL) {
temp = root->right;
}
else {
temp = root->left;
}
free(root);
return temp;
}
else {
struct BinaryTreeNode* temp
= findMin(root->right);
root->key = temp->key;
root->right = delete (root->right, temp->key);
}
}
return root;
}

int main()
{
// Initialize the root node
struct BinaryTreeNode* root = NULL;

// Insert nodes into the binary search tree


root = insertNode(root, 50);
insertNode(root, 30);
insertNode(root, 20);
insertNode(root, 40);
insertNode(root, 70);
insertNode(root, 60);

Page | 50
insertNode(root, 80);

// Search for a node with key 60


if (searchNode(root, 60) != NULL) {
printf("60 found");
}
else {
printf("60 not found");
}

printf("\n");

// Perform post-order traversal


postOrder(root);
printf("\n");

// Perform pre-order traversal


preOrder(root);
printf("\n");

// Perform in-order traversal


inOrder(root);
printf("\n");

// Perform delete the node (70)


struct BinaryTreeNode* temp = delete (root, 70);
printf("After Delete: \n");
inOrder(root);

// Free allocated memory (not done in this code, but


// good practice in real applications)

return 0;
}

AVL TREE
C program to insert a node in AVL tree
#include<stdio.h>
#include<stdlib.h>

// An AVL tree node


struct Node

Page | 51
{
int key;
struct Node *left;
struct Node *right;
int height;
};

// A utility function to get maximum of two integers


int max(int a, int b);

// A utility function to get the height of the tree


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

// A utility function to get maximum of two integers


int max(int a, int b)
{
return (a > b)? a : b;
}

/* Helper function that allocates a new node with the given key and
NULL left and right pointers. */
struct Node* newNode(int key)

Page | 52
{
struct Node* node = (struct Node*)
malloc(sizeof(struct Node));
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1; // new node is initially added at leaf
return(node);
}

// A utility function to right rotate subtree rooted with y


// See the diagram given above.
struct Node *rightRotate(struct Node *y)
{
struct Node *x = y->left;
struct Node *T2 = x->right;

// Perform rotation
x->right = y;
y->left = T2;

// Update heights
y->height = max(height(y->left), height(y->right))+1;
x->height = max(height(x->left), height(x->right))+1;

// Return new root


return x;

Page | 53
}

// A utility function to left rotate subtree rooted with x


// See the diagram given above.
struct Node *leftRotate(struct Node *x)
{
struct Node *y = x->right;
struct Node *T2 = y->left;

// Perform rotation
y->left = x;
x->right = T2;

// Update heights
x->height = max(height(x->left), height(x->right))+1;
y->height = max(height(y->left), height(y->right))+1;

// Return new root


return y;
}

// Get Balance factor of node N


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

Page | 54
}

// Recursive function to insert a key in the subtree rooted


// with node and returns the new root of the subtree.
struct Node* insert(struct Node* node, int key)
{
/* 1. Perform the normal BST insertion */
if (node == NULL)
return(newNode(key));

if (key < node->key)


node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
else // Equal keys are not allowed in BST
return node;

/* 2. Update height of this ancestor node */


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

/* 3. Get the balance factor of this ancestor


node to check whether this node became
unbalanced */
int balance = getBalance(node);

// If this node becomes unbalanced, then

Page | 55
// there are 4 cases

// Left Left Case


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

// Right Right Case


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

// Left Right Case


if (balance > 1 && key > node->left->key)
{
node->left = leftRotate(node->left);
return rightRotate(node);
}

// Right Left Case


if (balance < -1 && key < node->right->key)
{
node->right = rightRotate(node->right);
return leftRotate(node);
}

/* return the (unchanged) node pointer */


return node;
}

Page | 56
// A utility function to print preorder traversal
// of the tree.
// The function also prints height of every node
void preOrder(struct Node *root)
{
if(root != NULL)
{
printf("%d ", root->key);
preOrder(root->left);
preOrder(root->right);
}
}

/* Driver program to test above function*/


int main()
{
struct Node *root = NULL;

/* Constructing tree given in the above figure */


root = insert(root, 10);
root = insert(root, 20);
root = insert(root, 30);
root = insert(root, 40);
root = insert(root, 50);
root = insert(root, 25);

Page | 57
/* The constructed AVL Tree would be
30
/ \
20 40
/ \ \
10 25 50
*/

printf("Preorder traversal of the constructed AVL"


" tree is \n");
preOrder(root);
return 0;
}

Page | 58
UNIT 5
Shortest Path Algorithm
// C program for Dijkstra's single source shortest path
// algorithm. The program is for adjacency matrix
// representation of the graph

#include <limits.h>
#include <stdbool.h>
#include <stdio.h>

// Number of vertices in the graph


#define V 9

// A utility function to find the vertex with minimum


// distance value, from the set of vertices not yet included
// in shortest path tree
int minDistance(int dist[], bool sptSet[])
{
// Initialize min value
int min = INT_MAX, min_index;

for (int v = 0; v < V; v++)


if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;

return min_index;
}

// A utility function to print the constructed distance


// array
void printSolution(int dist[])
{
printf("Vertex \t\t Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t\t\t %d\n", i, dist[i]);
}

// Function that implements Dijkstra's single source


// shortest path algorithm for a graph represented using
// adjacency matrix representation
void dijkstra(int graph[V][V], int src)

Page | 59
{
int dist[V]; // The output array. dist[i] will hold the
// shortest
// distance from src to i

bool sptSet[V]; // sptSet[i] will be true if vertex i is


// included in shortest
// path tree or shortest distance from src to i is
// finalized

// Initialize all distances as INFINITE and stpSet[] as


// false
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;

// Distance of source vertex from itself is always 0


dist[src] = 0;

// Find shortest path for all vertices


for (int count = 0; count < V - 1; count++) {
// Pick the minimum distance vertex from the set of
// vertices not yet processed. u is always equal to
// src in the first iteration.
int u = minDistance(dist, sptSet);

// Mark the picked vertex as processed


sptSet[u] = true;

// Update dist value of the adjacent vertices of the


// picked vertex.
for (int v = 0; v < V; v++)

// Update dist[v] only if is not in sptSet,


// there is an edge from u to v, and total
// weight of path from src to v through u is
// smaller than current value of dist[v]
if (!sptSet[v] && graph[u][v]
&& dist[u] != INT_MAX
&& dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}

Page | 60
// print the constructed distance array
printSolution(dist);
}

// driver's code
int main()
{
/* Let us create the example graph discussed above */
int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };

// Function call
dijkstra(graph, 0);

return 0;
}

Page | 61

You might also like