0% found this document useful (0 votes)
13 views25 pages

Adobe Scan 21 Nov 2023

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)
13 views25 pages

Adobe Scan 21 Nov 2023

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/ 25

EXPERIMENT -6

Aim
Create a stack and perform PUSH, POP, PEEK and TRAVERSE
operations on the stack using the linked list.
Language Used
C Programming Language
Theory
Linked List implementation of stack
Instead of using array, we can also use linked list to implement
stack. Linked list allocates the memory dynamically. However,
time complexity n both the scenario is same for all the operations
i.e. push, pop and peek.
In linked list implementation of stack, the nodes are maintained
non-contiguously in the memory. Each node contains a pointer to
its immediate successor node in the stack. Stack is said to be
overflown if the space left in the memory heap is not enough to
createa node.

Algorithm
Push Operation:
" Initialize a node.
Update the value of that node by data i.e. node->data=data
Now link this node to the top of the linked list.
" And update top pointer to the current node.
Pop Operation:
First check whether there is any node present in the linked
list or not, if not then return.
Otherwise make pointer let say temp to the top node and
move forward the top node by 1 step.
Now free this temp node.
Peek Operation:
Check if there is any node present or not, if not then return.
Otherwise return the value of top node of the linked list.
Traversing Operation:
Take a temp node and initialize it with top pointer.
Now start traversing temp till it encounters NULL.
" Simultaneously print the value of the temp node.
Programn Code
#include <stdio . h>
#include <stdlib.h>
|// Define the structure for a stack node
struct Node {
int data;
struct Node* next;

struct Node* top = NULL;


// Function to check if the stack is empty
int isEmpty() {
return (top == NULL);

|// Function to push an element onto the stack


void push(int data) {
struct Node* newNode = (struct Node*) malloc (sizeof (struct
Node) ) ;
if (newNode == NULL) {
printf("Stack overflow. Unable to push %d. \n", data);
return ;

newNode- >data = data;


newNode->next = top;
top = newNode;
printf("Pushed %d onto the stack.\n", data);

|// Function to pop an element from the stack


int pop() {
if (isEmpty() ) {
printf("Stack is empty. Unable to pop. \n");
return -1;

struct Node* temp = top;


int data = temp- >data;
top = temp->next;
free(temp) ;
printf("Popped %d from the stack. \n", data);
return data;

|// Function to peek at the top element of the stack


int peek() {
if (isEmpty()) {
printf("Stack is empty. Unable to peek.\n");
return -1;

return top->data;
// Function to traverse and display the elements in the stack
void traverse() {
struct Node* current = top;
printf("Stack elements: ");
while (current != NULL) {
printf("%d ", current->data);
current = current->next;

printf("\n");

int main() {
int choice, data;
while (1) {
printf("\nStack Operations:\n");
printf("1. PUSH\n");
printf("2. POP\n");
printf("3. PEEK\n");
printf("4. TRAVERSE\n") ;
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter data to push: ");
scanf("%d", &data) ;
push(data);
break;
case 2:
data = pop();
if (data != -1) {
printf("Popped item: %d\n", data);
break;
case 3:
data = peek();
if (data != -1) {
printf("Top of the stack: %d\n", data);
break;
case 4:
traverse();
break;
case 5:
printf("Exiting the program. \n") ;
exit (0) ;
default:
printf("Invalid choice. Please try again. \n");
}
return 0;
Output
EXPERIMENT - 7
Aim
Create a linear queue using linked list and implement different
operations such as insert, delete and display the queue elements.
Language Used
C Programming Language
Theory
In linear queue, insertion is done from the rear and deletion is
done from the front end. In circular queue, the insertion and
deletion can take place from any end. The memory space occupied
by the linear queue is more than the circular queue. It requires
less memory as compared to linear queue.
Program Code
#include <stdio.h>
#include <stdlib.h>
// Define a structure for a node in the linked list
struct Node {
int data;
struct Node* next;

// Define a structure for the linear queue


struct Queue {
struct Node* front;
struct Node* rear;

/ Function to create an empty queue


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

|// Function to insert an element into the queue


void enqueue (struct Queue* queue, int item) {
struct Node* newNode = (struct Node*)malloc (sizeof (struct
|Node));
newNode->data = item;
newNode->next = NULL;
if (queue->rear == NULL) {
queue- >front = queue- >rear = newNode;
} else {
queue->rear- >next = newNode;
queue->rear = newNode;

printf("%d enqueued to the queue. \n", item);


// Function to delete an element from the queue
void dequeue(struct Queue* queue) {
if (queue->front = NULL) {
printf("Queue is empty. Cannot dequeue. \n");
return;

struct Node* temp = queue->front;


queue->front = queue->front->next;
| | If front becomes NULL, update rear to NULL as well
if (queue - >front == NULL) {
queue->rear = NULL;

printf( "%d dequeued from the queue. \n", temp->data) ;


free(temp);
}
void display (struct Queue* queue) {
if (queue->front == NULL) {
printf("Queue is empty. \n");
return;
}
printf("Queue elements: ");
struct Node* current = queue->front;
while (current != NULL) {
printf("%d", current->data);
current = current- >next;

printf("\n");
int main() {
struct Queue* queue = createQueue() ;
int choice, item;
while (1) {
printf(""\nQueue Operations : \n");
printf("1. Enqueue (Insert)\n");
printf("2. Dequeue (Delete)\n");
printf("3. Display\n" ) ;
printf("4. Exit\n");
printf("Enter your choice: ");
scanf( "%d", &choice) ;
Switch (choice) {
case 1:
printf("Enter the element to enqueue:");
scanf("%d", &item);
enqueue(queue, item);
break;
case 2:
dequeue(queue);
break;
case 3:
display(queue);
break;
case 4:
exit(0) ;
default:
printf("Invalid choice. Please try again. \n");

return 0;
Output
ldt section Vie Go un

DeBLE CONSOu

2. Dege (elete)

Enter yo c 2
engd to the gu,
Queue perat ions:
bej (belete)

4. Eit
r choices 1
Etee the e l e t to eege:
m d te the gee

3. olsplay

dequd frus the quus.


oeue perations:

. Oisplay

Enter the elent to enqane


enqueued to the queue

e tdt Selection ew Ge Run

PRORLEMS OutBUt OCUG CONO DCad

2. Dee (helete)

Entar your chtce


D

2. Orge (Delete)

Enter yor chelces 4


S Ciherspoonaetop
EXPERIMENT - 8
Aim
Create a binary tree and perform tree traversal (Inorder, Preorder,
Postorder) using the concept of recursion.
Language Used
C Programming Language
Theory
Abinary search tree (BST) is a binary tree with the following
properties:
" All items in the left subtree is less than root.
" Allitem in the right subtree are greater than or equal to root.
Each subtree is itself a binary search tree.
Inorder Traversal: Traversal start from the left most element of
the left subtree then the root of that element then right subtree of
that root and so on. In case of binary search tree inorder traversal
gives nodes in non-decreasing order.
Preorder Traversal: A traversal method, where the root node is
visited first, then left subtree and then the right subtree.
Postorder Traversal: A traversal method, where left subtree is
visited first, then right subtree and finally root node.
Program Code
#include <stdio.h>
#include <stdlib. h>
/ Define a structure for anode in the binary tree
struct Node {
int data;
struct Node* left;
struct Node* right;

|// Function to create a new node


struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc (sizeof (struct
Node) );
newNode- >data = data;
newNode->left = newNode->right = NULL;
return newNode;

|// Function to insert a node into the binary tree


struct Node* insertNode(struct Node* root, int data) {
if (root == NULL) {
return createNode(data);

if (data < root->data) {


root->left = insertNode(root->left, data);
}else if (data > root->data) {
root->right = insertNode (root->right, data) ;

return root;

|// Function to perform inorder tree traversal


void inorderTraversal (struct Node* root) {
if (root != NULL) {
inorderTraversal (root- >left) ;
printf("%d ", root->data);
inorderTraversal(root- >right);

// Function to perform preorder tree traversal


void preorderTraversal(struct Node* root) {
if (root != NULL) {
printf( "%d ", root- >data);
preorderTraversal(root->left);
preorderTraversal (root->right);
|// Function to perform postorder tree traversal
void postorderTraversal(struct Node* root) {
if (root != NULL) {
postorderTraversal(root->left);
postorderTraversal (root->right);
printf("%d ", root- >data);

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

printf("Binary Tree Operations : \n");


while (1) {
printf("1. Insert Node\n");
printf("2. Inorder Traversal\n");
printf("3. Preorder Traversal\n ");
printf("4. Postorder Traversal\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf( "%d", &choice) ;

Switch (choice) {
case 1:

printf("Enter data to insert: ");


scanf("%d", &data);
root = insertNode (root, data);
break;
case 2:
printf("Inorder Traversal: ");
inorderTraversal(root);
printf("\n");
break;
case 3:

printf("Preorder Traversal: ");


preorderTraversal (root) ;
printf("\n");
break;
case 4:

printf("Postorder Traversal: ");


postorderTraversal (root );
printf("\n");
break;
case 5:
exit (0) ;
default:
printf(" Invalid choice. Please try again.\n");
return 0;
EXPERIMENT - 9
Aim
Implement Insertion, Deletion and Traversals (Inorder, Preorder
and Postorder) on Binary Search Tree about the details of an
automobile (type, company, year of make)
Language Used
C Programming Language

Theory
Abinary search tree follows some order to arrange the elements.
In aBinary Search Tree, the value of left mode must be smaller
than the parent node and the value of right node must be greater
than the parent node. This rule is applied recursively tothe left
and right subtrees of the root.
Insertion and Deletion: Operations such as insertion and
deletion cause the BST representation to change dynamically. The
data structure must be modified in such a way that the properties
of BST continue to hold. New nodes are inserted as leaf nodes in
the BST.
Traversal: ABST can be traversed through three basic
algorithms: inorder, preorder and postorder tree walks.
Inorder tree walk: Nodes from the left subtree get visited
first, followed by the root node and right subtree. Such a
traversal visit all the nodes in the order of non-decreasing
key sequence.
" Preorder tree walk: The root node gets visited first,
followed by left and right subtrees.
Postorder tree walk: Nodes from the left subtree get
visited first, followed by the right subtree and finally the
root.
Programn Code
#include <stdio.h>
#include <stdlib.h>
// Define a structure to represent an automobile
struct Automobile {
char type[ 50];
char company[50] ;
int year_of_make;
};
|// Define the structure for a BST node
struct BSTNode {
struct Automobile data;
struct BSTNode* left;
struct BSTNode* right;

|// Function to create a new BST node


struct BSTNode* createNode (struct Automobile data) {
struct BSTNode* newNode = (struct BSTNode* )malloc (sizeof (struct
BSTNode) );
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
|// Function to insert a node into the BST
struct BSTNOde* insert(struct BSTNOde* root, struct Automobile data)

if (root == NULL) {
return createNode(data);
if (data.year_of_make < root->data.year_of_make) {
root->left = insert (root ->left, data);
} else if (data.year_of_make > root->data.year_of_make) {
root->right = insert (root->right, data);
return root;

|// Function to find the minimum node in a BST


struct BSTNOde* findMin(struct BSTNOde* root) {
while (root- >left != NULL) {
root = root->left;

return root;
}
|// Function to delete a node from the BST
struct BSTNode* deleteNode (struct BSTNode* root, int year) {
if (root == NULL) {
return root;
if (year < root- >data.year_of_make) {
root->left = deleteNode(root->left, year);
} else if (year > root->data.year _of_make) {
root->right = deleteNode (root->right, year) ;
} else {
1/ Node with only one child or no child
if (root->left == NULL) {
struct BSTNode* temp = root->right;
free (root) ;
return temp;
} else if (root->right == NULL) {
struct BSTNode* temp = root->left;
free(root);
return temp;

/ Node with two children, get the in-order successor


(smallest in the right subtree)
struct BSTNode* temp = findMin (root- >right);
1/ Copy the in-order successor's data to this node
root->data = temp- >data;
1/ Delete the in-order successor
root->right = deleteNode (root->right, temp
>data.year_of_make);
return root;

|//Function for in-order traversal


void inorderTraversal (struct BSTNode* root) {
if (root != NULL) {
inorderTraversal(root->left);
printf(" Type: %s, Company: %s, Year: %d\n", root->data.type,
root- >data.company, root- >data.year_of_make) ;
inorderTraversal (root->right);

// Function for pre-order traversal


void preorderTraversal(struct BSTNode* root) {
if (root != NULL) {
printf("Type: %s, Company: %s, Year: %d\n", root ->data.type,
root->data.company, root->data.year_of _make);
preorderTraversal (root->left);
preorderTraversal (root->right);

|// Function for post-order traversal


void postorderTraversal(struct BSTNode* root) {
if (root != NULL) {
postorderTraversal (root - >left);
postorderTraversal (root ->right) ;
printf("Type: %s, Company: %s, Year: %d\n", root->data.type,
root->data.company, root->data.year_of_make);

|int main() {
struct BSTNode* root = NULL;
struct Automobile car1 = { "Sedan", "Toyota", 2020 };
struct Automobile car2 = { "SUV", "Ford", 2019 };
struct Automobile car3 = { "Hatchback", "Honda", 2022 };
struct Automobile car4 = { "Convertible", "Chevrolet", 2018 };
root = insert (root, car1);
root = insert(root, car2) ;
root = insert (root, car3) ;
root = insert(root, car4);
printf("Inorder Traversal:\n");
inorderTraversal(root);
int yearToDelete = 2019;
root = deleteNode (root, yearToDelete);
printf("\nInorder Traversal after deleting a node: \n");
inorderTraversal(root) ;

printf("\nPreorder Traversal: \n");


preorderTraversal (root) ;
printf("\nPostorder Traversal:\n");
postorderTraversal(root);

return 0;
Output
e fdt Selection View Go Run

PeceLEVS ouTPUT peBLKS CONEOLE TEBAE PORTS

Ps C:es\poana\eatplc> cd
Inorder Iraversal:
sers\poonaesktep\C1" ;1f (9) ( e e 1: 1f S) (.ube)
y evrolet, ear: 21a

type: Sedan, Copay: loyta, Vear: 282e


Types Hatchback, Canpany: onda, Vear: 2022
Iurdar lraversal
Ivee: Sedt CRt detirst 281
ta
ode
0
type: atdhhack, Copany: snda, Yar: 2022
Preorder Traversal:
yp Sea t vars 21a
Type: atchtack, Campany: inda, Year: 22
Postordr Iraversal:
yp cavertible, Copayi Cevrolet, ear: 2018
Iye: Sedat. CaRt tot
P5 CihesipoanaektoplC
EXPERIMENT - 10
Aim
Create a graph and perform DFS and BFS traversals.
Language Used
CProgramming Language

Theory
Graph: Graph is a non-linear data structure made up of finite
number of nodes or vertices and the edges that connect them.
Graphs in data structure are used to address real-world problems
in which it represents the problem area as a network like
telephone networks,circuit networks and social networks.
Depth First Search (DFS): Unlike trees, graphs may contain
cycles (a node may be visited twice). To avoid processing a node
more than once, use a boolean visited array. A graph can have
more than one DFS traversal.
Breadth First Search (BFS): BFS is used to search a graph data
structure for a node that meets a set of criteria. It starts at the
root of the graph and visits all nodes at the current depth level
before moving on to the nodes at the next depth level.
Program Code
#include <stdio.h>
#include <stdlib.h>
#include <stdbool . h>
#define MAX NODES 100

1/ Structure to represent a node in the adjacency list


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

|// Structure to represent the graph


struct Graph {
int numNodes;
struct Node* adjacencyList [MAX_NODES ];

|// Create a new graph with a specified number of nodes


struct Graph* createGraph (int numNodes) {
struct Graph* graph = (struct Graph* )malloc (sizeof (struct
|Graph)) ;
graph->numNodes = numNodes;

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


graph->adjacencyList [i] = NULL;

return graph;

|//Add an edge between two nodes in the graph


|void addEdge(struct Graph* graph, int src, int dest) {
struct Node* newNode = (struct Node*) malloc (sizeof (struct
Node) );
newNode->data = dest;
newNode ->next = graph->adjacencyList [src];
graph->adjacencyList[src] = newNode;
// For undirected graph, add an edge from dest to src as well
newNode = (struct Node*)malloc (sizeof (struct Node));
newNode->data = srC;
newNode->next = graph->adjacencyList [dest];
graph->adjacencyList [dest ] = newNode;
|// Depth-First Search (DFS) traversal
void DFs (struct Graph* graph, int node, bool visited[]) {
visited[node] = true;
printf( "%d ", node) ;

struct Node* current = graph->adjacencyList [node];


while (current != NULL) {
int neighbor = current->data;
if (!visited[neighbor]) {
DFS (graph, neighbor, visited);
current = current->next;

|// Breadth-First Search (BFS) traversal


void BFS (struct Graph* graph, int start) {
bool visited[MAX_NODES] = {false};
int queue[MAX_NODES ];
int front 0, rear = 0;

visited[start] = true;
queue[rear++] = start;

printf("Breadth-First Traversal: ");


while (front < rear) {
int node = queue[front++];
printf("%d", node);

struct Node* current = graph->adjacencyList [node] ;


while (current != NULL) {
int neighbor = current->data;
if (!visited[neighbor]) {
visited[neighbor] = true;
queue [rear++] = neighbor;
current = current->next;

}
printf("\n");

|int main() {
int numNodes, numEdges;
printf("Enter the number of nodes and edges: ");
scanf ("%d %d", &numNodes, &numEdges);
struct Graph* graph = createGraph(numNodes);
printf("Enter the edges (src dest):\n");
for (int i = 0; i< numEdges; i++) {
int src, dest;
scanf( "%d %d", &src, &dest) ;
addEdge (graph, src, dest);

int startNode;
printf("Enter the starting node for BFS: ");
scanf("%d", &startNode) ;
printf("Depth-First Traversal: ");
bool visited [MAX_NODES] = (false);
for (int i =0; i< numNodes; i++) {
if (!visited[i]) {
DFS(graph, i, visited);

printf("\n");

BFS (graph, startNode);


return 0;
Output
e Edt Selectson View Ce Run

PRORLEMS oUTT DESUG COSOLE TEmeNL PORTS

cytpc cusrs\pocnaektg\C\ f (9 lec b.ctc); 1f () ( e )


Enter the edes (src dst):

Enter the starting node for S : 3

PS C:sers\poonaesktup\C>

You might also like