Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Data Structure Lab (MCA-6251)

The document contains multiple C programming code snippets that implement various algorithms and data structures. Key functionalities include bubble sort, Tower of Hanoi (both recursive and non-recursive), linked list operations (insertion, deletion, display), minimum spanning tree algorithms (Prim's and Kruskal's), and depth-first search (DFS) using a stack. Each section includes user prompts for input and outputs the results of the operations performed.

Uploaded by

Manish Shrestha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Data Structure Lab (MCA-6251)

The document contains multiple C programming code snippets that implement various algorithms and data structures. Key functionalities include bubble sort, Tower of Hanoi (both recursive and non-recursive), linked list operations (insertion, deletion, display), minimum spanning tree algorithms (Prim's and Kruskal's), and depth-first search (DFS) using a stack. Each section includes user prompts for input and outputs the results of the operations performed.

Uploaded by

Manish Shrestha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Q1a

#include <stdio.h>
void bubble_sort(int[], int);
int main() {
int a[100], n;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements: ", n);
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
bubble_sort(a, n);
printf("\nSorted Elements: \n");
for (int i = 0; i < n; i++)
printf("%d\n", a[i]);
return 0;
}
void bubble_sort(int x[], int y) {
int swap;
for (int i = 0; i < y - 1; i++) {
for (int j = 0; j < y - 1 - i; j++) {
if (x[j] > x[j + 1]) {
swap = x[j];
x[j] = x[j + 1];
x[j + 1] = swap;
}
}
}
}
Q2a
#include<stdio.h>

void hanoiNonRecursion(int num, char sndl, char indl, char dndl) {


char stkn[50], stksndl[50], stkindl[50], stkdndl[50], stkadd[50], temp;
int top = -1, add;

one:
if(num == 1) {
printf("\nMove top disk from needle %c to needle %c\n", sndl, dndl);
goto four;
}

two:
top++;
stkn[top] = num;
stksndl[top] = sndl;
stkindl[top] = indl;
stkdndl[top] = dndl;
stkadd[top] = 3;
num--;
sndl = sndl;
temp = indl;
indl = dndl;
dndl = temp;
goto one;

three:
printf("\nMove top disk from needle %c to needle %c\n", sndl, dndl);
top++;
stkn[top] = num;
stksndl[top] = sndl;
stkindl[top] = indl;
stkdndl[top] = dndl;
stkadd[top] = 5;
num--;
temp = sndl;
sndl = indl;
indl = temp;
dndl = dndl;
goto one;

four:
if(top == -1)
return;
num = stkn[top];
sndl = stksndl[top];
indl = stkindl[top];
dndl = stkdndl[top];
add = stkadd[top];
top--;
if(add == 3)
goto three;
else if(add == 5)
goto four;
}

void hanoiRecursion(int num, char ndl1, char ndl2, char ndl3) {


if (num == 1) {
printf("\nMove top disk from needle %c to needle %c.\n", ndl1, ndl2);
return;
}
hanoiRecursion(num - 1, ndl1, ndl3, ndl2);
printf("Move top disk from needle %c to needle %c.\n", ndl1, ndl2);
hanoiRecursion(num - 1, ndl3, ndl2, ndl1);
}

int main() {
int no;
printf("Enter the number of disks to be transferred: ");
scanf("%d", &no);
if(no < 1)
printf("There's nothing to move.\n");
else {
printf("\nNon-Recursive:\n");
hanoiNonRecursion(no, 'A', 'B', 'C');

printf("\nRecursive:\n");
hanoiRecursion(no, 'A', 'B', 'C');
}
return 0;
}
Q3a

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

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

// Function to create a new node


struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed!\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to insert a node at the beginning of a sorted linked list


struct Node* insertSorted(struct Node* head, int data) {
struct Node* newNode = createNode(data);
if (head == NULL || data < head->data) {
newNode->next = head;
return newNode;
}
struct Node* current = head;
while (current->next != NULL && current->next->data < data) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
return head;
}

// Function to delete the first node of the linked list


struct Node* deleteFirstNode(struct Node* head) {
if (head == NULL) {
printf("List is empty. Nothing to delete.\n");
return NULL;
}
struct Node* temp = head;
head = head->next;
free(temp);
printf("First node deleted.\n");
return head;
}

// Function to display the linked list


void displayList(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}

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

while (1) {
printf("\nLinked List Operations:\n");
printf("1. Insertion at beginning in sorted list\n");
printf("2. Deletion of first node\n");
printf("3. Display the list\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter data to insert: ");
scanf("%d", &data);
head = insertSorted(head, data);
printf("Node inserted.\n");
break;
case 2:
head = deleteFirstNode(head);
break;
case 3:
printf("Current linked list: ");
displayList(head);
break;
case 4:
printf("Exiting program.\n");
exit(0);
default:
printf("Invalid choice! Please enter a valid option.\n");
}
}

return 0;
}
#include <stdio.h>
#include <stdlib.h>

void prints(int n, int cost[10][10]) {


int i, j, u = 0, v = 0, min, mincost = 0;
int visited[10] = {0};
int ne = 1;

visited[0] = 1;

printf("The edges considered for the MST are:\n");


while (ne < n) {
for (i = 0, min = 999; i < n; i++) {
for (j = 0; j < n; j++) {
if (cost[i][j] < min) {
if (visited[i] == 0) {
continue;
} else {
min = cost[i][j];
u = i;
v = j;
}
}
}
}

if (visited[u] == 1 && visited[v] == 0) {


printf("Edge %d: (%d, %d) cost: %d\n", ne++, u, v, min);
mincost += min;
visited[v] = 1;
}

cost[u][v] = cost[v][u] = 999;


}

printf("Minimum cost = %d\n", mincost);


}

int main() {
int i, j, n;
int cost[10][10];

// Prompt the user to enter the number of nodes


printf("Enter number of nodes: ");
scanf("%d", &n);

// Prompt the user to enter the cost matrix


printf("Enter the cost matrix:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &cost[i][j]);
// Replace 0 with 999 to indicate no direct connection
if (cost[i][j] == 0) {
cost[i][j] = 999;
}
}
}

// Call the prints function to calculate and print the MST


prints(n, cost);

return 0;
}
Q4b
#include <stdio.h>
#include <stdlib.h>

#define MAX 10

typedef struct Edge {


int u, v, weight;
} Edge;

typedef struct Graph {


int V, E;
Edge edges[MAX];
} Graph;

int find(int parent[], int i) {


if (parent[i] == i)
return i;
return find(parent, parent[i]);
}

void unionSets(int parent[], int rank[], int u, int v) {


int rootU = find(parent, u);
int rootV = find(parent, v);

if (rank[rootU] < rank[rootV])


parent[rootU] = rootV;
else if (rank[rootU] > rank[rootV])
parent[rootV] = rootU;
else {
parent[rootV] = rootU;
rank[rootU]++;
}
}

int compareEdges(const void* a, const void* b) {


Edge* edgeA = (Edge*)a;
Edge* edgeB = (Edge*)b;
return edgeA->weight - edgeB->weight;
}

void kruskalMST(Graph* graph) {


int V = graph->V;
Edge result[MAX]; // To store the resultant MST
int e = 0; // An index variable, used for result[]
int i = 0; // An index variable, used for sorted edges

// Step 1: Sort all the edges in non-decreasing order of their weight


qsort(graph->edges, graph->E, sizeof(graph->edges[0]), compareEdges);
int parent[MAX];
int rank[MAX];

// Step 2: Create V subsets with single elements


for (int v = 0; v < V; v++) {
parent[v] = v;
rank[v] = 0;
}

// Number of edges to be taken is equal to V-1


while (e < V - 1 && i < graph->E) {
// Step 3: Pick the smallest edge. Check if it forms a cycle with the spanning tree formed
so far. If not, include it in the result. Else, discard it.
Edge next_edge = graph->edges[i++];

int x = find(parent, next_edge.u);


int y = find(parent, next_edge.v);

// If including this edge doesn't cause a cycle, include it in the result and increment the
index of result for next edge
if (x != y) {
result[e++] = next_edge;
unionSets(parent, rank, x, y);
}
// Else discard the next_edge
}

// Print the constructed MST


printf("The edges included in the MST are:\n");
int minimumCost = 0;
for (i = 0; i < e; i++) {
printf("Edge: (%d, %d) cost: %d\n", result[i].u, result[i].v, result[i].weight);
minimumCost += result[i].weight;
}
printf("Minimum cost = %d\n", minimumCost);
}

int main() {
int n, E;
Graph graph;

// Prompt the user to enter the number of nodes and edges


printf("Enter the number of nodes: ");
scanf("%d", &n);
graph.V = n;

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


scanf("%d", &E);
graph.E = E;
// Prompt the user to enter each edge with its weight
printf("Enter the edges (u v weight):\n");
for (int i = 0; i < E; i++) {
scanf("%d %d %d", &graph.edges[i].u, &graph.edges[i].v, &graph.edges[i].weight);
}

// Call the kruskalMST function to calculate and print the MST


kruskalMST(&graph);

return 0;
}
Q5b
#include <stdio.h>
#include <stdlib.h>

#define MAX 100 // Maximum number of nodes

typedef struct Stack {


int data[MAX];
int top;
} Stack;

void initStack(Stack *s) {


s->top = -1;
}

int isEmpty(Stack *s) {


return s->top == -1;
}

void push(Stack *s, int value) {


if (s->top < MAX - 1) {
s->data[++(s->top)] = value;
} else {
printf("Stack overflow\n");
}
}

int pop(Stack *s) {


if (!isEmpty(s)) {
return s->data[(s->top)--];
} else {
printf("Stack underflow\n");
return -1;
}
}

void DFS(int graph[MAX][MAX], int n, int start) {


Stack stack;
initStack(&stack);

int visited[MAX] = {0}; // Initialize all nodes as unvisited

push(&stack, start);
visited[start] = 1;

printf("DFS traversal starting from node %d:\n", start);

while (!isEmpty(&stack)) {
int node = pop(&stack);
printf("%d ", node);
// Visit all adjacent unvisited nodes
for (int i = 0; i < n; i++) {
if (graph[node][i] == 1 && !visited[i]) {
push(&stack, i);
visited[i] = 1;
}
}
}

printf("\n");
}

int main() {
int n, start;
int graph[MAX][MAX];

// Read the number of nodes


printf("Enter the number of nodes: ");
scanf("%d", &n);

// Read the adjacency matrix


printf("Enter the adjacency matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &graph[i][j]);
}
}

// Read the starting node for DFS


printf("Enter the starting node: ");
scanf("%d", &start);

// Perform DFS
DFS(graph, n, start);

return 0;
}

You might also like