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

data_structure_fina Journal

The document is a practical journal for a Data Structure course, containing various programming exercises related to data structures such as Binary Search Trees, polynomial evaluation, string reversal using stacks, and linked lists. Each exercise includes code snippets in C/C++ demonstrating the implementation of the respective data structure and its operations. The journal serves as a practical guide for students to understand and apply data structure concepts through hands-on coding.

Uploaded by

Ashish Medhe
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)
22 views

data_structure_fina Journal

The document is a practical journal for a Data Structure course, containing various programming exercises related to data structures such as Binary Search Trees, polynomial evaluation, string reversal using stacks, and linked lists. Each exercise includes code snippets in C/C++ demonstrating the implementation of the respective data structure and its operations. The journal serves as a practical guide for students to understand and apply data structure concepts through hands-on coding.

Uploaded by

Ashish Medhe
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/ 53

SEM III {PRACTICAL JOURNAL}

DATA
STRUCTURE
{TOTAL SIXTEEN SLIPS}

SUSHMITHAA PANDIDHAR
SY BBA {CA}
304: DATA STRUCTURE
1. Slip 1A Binary Search Tree Create,Insert & Delete & InOrder Traversing
Code:
#include <iostream>
using namespace std;

// Node structure for the Binary Search Tree


struct Node {
int data;
Node* left;
Node* right;

Node(int value) {
data = value;
left = right = nullptr;
}
};

// Class for Binary Search Tree


class BST {
public:
Node* root;

BST() {
root = nullptr;
}

// Function to insert a new node


Node* insert(Node* root, int value) {
if (root == nullptr) {
return new Node(value);
}

if (value < root->data) {


root->left = insert(root->left, value);
} else {
root->right = insert(root->right, value);
}

return root;
}

// Function to perform in-order traversal


void inOrder(Node* root) {
if (root == nullptr) {
return;
}

inOrder(root->left);
cout << root->data << " ";
inOrder(root->right);
}

// Function to find the minimum value in the tree (used in deletion)


Node* findMin(Node* root) {
while (root->left != nullptr) {
root = root->left;
}
return root;
}

// Function to delete a node


Node* deleteNode(Node* root, int value) {
if (root == nullptr) {
return root;
}

if (value < root->data) {


root->left = deleteNode(root->left, value);
} else if (value > root->data) {
root->right = deleteNode(root->right, value);
} else {
// Node with only one child or no child
if (root->left == nullptr) {
Node* temp = root->right;
delete root;
return temp;
} else if (root->right == nullptr) {
Node* temp = root->left;
delete root;
return temp;
}

// Node with two children


Node* temp = findMin(root->right);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}

return root;
}
};

int main() {
BST bst;
bst.root = bst.insert(bst.root, 50);
bst.insert(bst.root, 30);
bst.insert(bst.root, 20);
bst.insert(bst.root, 40);
bst.insert(bst.root, 70);
bst.insert(bst.root, 60);
bst.insert(bst.root, 80);

cout << "In-order traversal of the BST: ";


bst.inOrder(bst.root);
cout << endl;

cout << "Deleting 20\n";


bst.root = bst.deleteNode(bst.root, 20);
cout << "In-order traversal after deletion: ";
bst.inOrder(bst.root);
cout << endl;

cout << "Deleting 30\n";


bst.root = bst.deleteNode(bst.root, 30);
cout << "In-order traversal after deletion: ";
bst.inOrder(bst.root);
cout << endl;

cout << "Deleting 50\n";


bst.root = bst.deleteNode(bst.root, 50);
cout << "In-order traversal after deletion: ";
bst.inOrder(bst.root);
cout << endl;

return 0;
}
Output:

2. Slip 1B Evalution of polynomial:


CODE:
#include<stdio.h>
#include<conio.h>
#include<math.h>

int eval(int a[],int n,int x)


{
int i;
double p,sum=0;
for(i=n;i>=0;i--)
{
p=pow(x,i);
sum=sum+a[i]*p;
}
return sum;
}

void main()
{
int a[10],n,c,i,e,x;
printf("Enter the Degree of polynomial : ");
scanf("%d",&n);
printf("\n Enter the coefficient : ");
for(i=n;i>=0;i--)
{
printf("\n Enter coefficient A[%d]",i);
scanf("%d",&a[i]);
}
printf("\n Enter the polynomial : ");

for(i=n;i>=0;i--)
{
if(a[i]!=0)
printf("%dX^%d + ",a[i],i);
}
printf("%d",a[i]);

printf("\n Enter the value for X ");


scanf("%d",&x);
e=eval(a,n,x);
printf("\n Evalution of polynomaial is = %d",e);
getch();
}
3. Slip 2A- Reverse the string using static Implementation of Stack
CODE:
#include <stdio.h>
#include <string.h>

#define MAX 100 // Maximum size of stack

// Stack structure
struct Stack {
int top;
char items[MAX]; // Array of characters (for the string)
};

// Function to initialize the stack


void initialize(struct Stack* s) {
s->top = -1; // Set the stack to empty
}

// Function to check if the stack is full


int isFull(struct Stack* s) {
return s->top == MAX - 1;
}

// Function to check if the stack is empty


int isEmpty(struct Stack* s) {
return s->top == -1;
}

// Function to push an element onto the stack


void push(struct Stack* s, char item) {
if (isFull(s)) {
printf("Stack Overflow\n");
return;
}
s->items[++(s->top)] = item;
}

// Function to pop an element from the stack


char pop(struct Stack* s) {
if (isEmpty(s)) {
printf("Stack Underflow\n");
return '\0'; // Return null character if stack is empty
}
return s->items[(s->top)--];
}

// Function to reverse the string using stack


void reverseString(char str[]) {
struct Stack s;
initialize(&s);

int i;
// Push all characters of the string into the stack
for (i = 0; i < strlen(str); i++) {
push(&s, str[i]);
}

// Pop all characters from the stack and put them back into the string
for (i = 0; i < strlen(str); i++) {
str[i] = pop(&s);
}
}

int main() {
char str[MAX];

// Input the string


printf("Enter a string: ");
gets(str); // Note: `gets` is not safe, it's better to use `fgets` in real-world scenarios

// Reverse the string


reverseString(str);
// Output the reversed string
printf("Reversed string: %s\n", str);

return 0;
}
OUTPUT:

4. Menu driven program for singly link list


CODE:
#include<stdio.h>
#include<stdlib.h> // For malloc and exit()

#define NA (struct node *)malloc(sizeof(struct node))

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

typedef struct node * NP;

// Prototype declaration
NP create();
void disp(NP start);
NP insert(NP start, int info);
NP del(NP start, int pos);

int main() {
NP start = NULL;
int ch, pos, info;

while (1) {
printf("\n1: Create\n2: Display\n3: Insert\n4: Delete\n5: Exit\n");
printf("Enter your choice: ");
scanf("%d", &ch);
switch (ch) {
case 1:
start = create();
break;
case 2:
disp(start);
break;
case 3:
printf("Enter information: ");
scanf("%d", &info);
start = insert(start, info);
break;
case 4:
printf("Enter position of node to delete: ");
scanf("%d", &pos);
start = del(start, pos);
break;
case 5:
exit(0);
default:
printf("Invalid choice, please try again.\n");
}
}
return 0;
}

// Create a linked list


NP create() {
NP start = NULL, temp, nn;
int n, i;
printf("How many nodes to insert: ");
scanf("%d", &n);
printf("Enter the list information:\n");
for (i = 0; i < n; i++) {
nn = NA;
nn->next = NULL;
scanf("%d", &nn->data);
if (start == NULL)
start = temp = nn;
else {
temp->next = nn;
temp = nn;
}
}
return start;
}

// Display the linked list


void disp(NP start) {
NP temp;
if (start == NULL) {
printf("List is empty.\n");
return;
}
for (temp = start; temp != NULL; temp = temp->next)
printf("%d\t", temp->data);
printf("\n");
}

// Insert at the beginning of the list


NP insert(NP start, int info) {
NP nn;
nn = NA;
nn->data = info;
nn->next = start; // New node points to the current start
start = nn; // Start now points to the new node
return start;
}

// Delete a node from the given position


NP del(NP start, int pos) {
NP temp = start, prev;
int i;

// If the list is empty


if (start == NULL) {
printf("List is empty.\n");
return start;
}

// If deleting the first node


if (pos == 1) {
start = start->next;
free(temp);
return start;
}

// Traverse the list to find the node at position (pos - 1)


for (i = 1; i < pos - 1 && temp != NULL; i++) {
temp = temp->next;
}

// If position is invalid or out of range


if (temp == NULL || temp->next == NULL) {
printf("Invalid position.\n");
return start;
}

// Deleting the node at the desired position


prev = temp->next; // Store the node to be deleted
temp->next = prev->next; // Bypass the node
free(prev); // Free the memory of the deleted node
return start;
}
OUTPUT:

5. Slip 4A Tree traversing


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

// Define the structure for a node in the binary search tree


struct NODE {
struct NODE *lchild;
int data;
struct NODE *rchild;
};
typedef struct NODE node;

// Function to allocate memory and get a new node


node* getnode() {
node *temp;
temp = (node *)malloc(sizeof(node));
printf("\nEnter the data: ");
scanf("%d", &temp->data);
temp->lchild = NULL;
temp->rchild = NULL;
return temp;
}

// Function to create the binary search tree


node* create() {
node *root = NULL, *temp, *ptr;
char ch;

do {
temp = getnode();
if (root == NULL) {
root = temp;
} else {
ptr = root;
while (ptr != NULL) {
if (temp->data < ptr->data) {
if (ptr->lchild == NULL) {
ptr->lchild = temp;
break;
} else {
ptr = ptr->lchild;
}
} else {
if (ptr->rchild == NULL) {
ptr->rchild = temp;
break;
} else {
ptr = ptr->rchild;
}
}
}
}

printf("\nDo you want to add more nodes (Y/N): ");


scanf(" %c", &ch); // Space before %c is important to consume any
newline
} while (ch == 'Y' || ch == 'y');

return root;
}

// Inorder traversal (left, root, right)


void inorder(node *ptr) {
if (ptr != NULL) {
inorder(ptr->lchild);
printf(" %d", ptr->data);
inorder(ptr->rchild);
}
}

// Postorder traversal (left, right, root)


void postorder(node *ptr) {
if (ptr != NULL) {
postorder(ptr->lchild);
postorder(ptr->rchild);
printf(" %d", ptr->data);
}
}

// Main function to provide the menu-driven interface


int main() {
int ch;
node *root = NULL;

while (1) {
printf("\n\nMenu:\n");
printf("1: Create a BST\n");
printf("2: Inorder Traversal of BST\n");
printf("3: Postorder Traversal of BST\n");
printf("4: Exit\n");
printf("Enter your choice: ");
scanf("%d", &ch);

switch (ch) {
case 1:
root = create();
break;
case 2:
printf("\nInorder Traversal: ");
inorder(root);
break;
case 3:
printf("\nPostorder Traversal: ");
postorder(root);
break;
case 4:
exit(0);
default:
printf("\nInvalid choice. Please try again.\n");
}
}

return 0;
}
OUTPUT:

6. Slip 5A Tree Traversal In Order,Post Order


CODE:

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

// Define the structure for a node in the binary search tree


struct NODE {
struct NODE *lchild;
int data;
struct NODE *rchild;
};

typedef struct NODE node;

// Function to allocate memory for a new node and get data from the user
node* getnode() {
node *temp = (node *)malloc(sizeof(node));
if (temp == NULL) {
printf("Memory allocation failed!\n");
exit(1); // Exit if memory allocation fails
}
printf("\nEnter the data: ");
scanf("%d", &temp->data);
temp->lchild = NULL;
temp->rchild = NULL;
return temp;
}

// Function to create a binary search tree


node* create() {
char ch;
node *root = NULL, *temp, *ptr;

do {
temp = getnode();
if (root == NULL) {
root = temp; // Initialize root if tree is empty
} else {
ptr = root; // Start from root to find the position
while (1) {
if (temp->data < ptr->data) {
if (ptr->lchild == NULL) {
ptr->lchild = temp; // Insert as left child
break;
} else {
ptr = ptr->lchild; // Move to left child
}
} else {
if (ptr->rchild == NULL) {
ptr->rchild = temp; // Insert as right child
break;
} else {
ptr = ptr->rchild; // Move to right child
}
}
}
}
printf("\nDo you want to add more nodes (Y/N): ");
scanf(" %c", &ch); // Read user response
} while (ch == 'Y' || ch == 'y');

return root;
}

// Inorder traversal of the binary search tree


void inorder(node *ptr) {
if (ptr != NULL) {
inorder(ptr->lchild);
printf(" %d", ptr->data);
inorder(ptr->rchild);
}
}

// Preorder traversal of the binary search tree


void preorder(node *ptr) {
if (ptr != NULL) {
printf(" %d", ptr->data);
preorder(ptr->lchild);
preorder(ptr->rchild);
}
}

// Main function
int main() {
int ch;
node *root = NULL;
while (1) {
printf("\n1: Create a BST.");
printf("\n2: Inorder of BST.");
printf("\n3: Preorder of BST.");
printf("\n4: Exit");
printf("\nEnter your choice: ");
scanf("%d", &ch);

switch (ch) {
case 1:
root = create();
break;
case 2:
printf("Inorder Traversal:");
inorder(root);
printf("\n");
break;
case 3:
printf("Preorder Traversal:");
preorder(root);
printf("\n");
break;
case 4:
exit(0);
default:
printf("Invalid choice, please try again.\n");
}
}
return 0; // Return success
}
OUTPUT:

7. Slip 5B -SLL node from number:


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

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

typedef struct NODE node;


node *list=NULL,*last;

node *getnodenum(int digit) // create a node


{
node *temp;
temp = (node *)malloc(sizeof(node));
temp->data = digit;
temp->next = NULL;
return temp;
}

void createnumll(int num)


{
int rem;
node *temp;
while (num > 0)
{
rem = num % 10;
num = num / 10;
temp = getnodenum(rem);
if (list == NULL)
list = temp;
else
{
temp->next = list;
list = temp;
}
}
}

void display()
{
node *ptr;
for (ptr = list; ptr != NULL; ptr = ptr->next)
printf("%d->", ptr->data);
printf("NULL");
}

void main()
{
int num;
printf("\nEnter the No: ");
scanf("%d", &num);
createnumll(num);
printf("\nLinked after separating the digits of num: ");
display();
}
OUTPUT:

8. Slip 6A -BST Inorder & Pre Order


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

struct NODE {
struct NODE *lchild;
int data;
struct NODE *rchild;
};

typedef struct NODE node;

node* getnode() {
node *temp = (node *)malloc(sizeof(node));
if (!temp) {
printf("Memory allocation failed!\n");
exit(1); // Exit if memory allocation fails
}
printf("\nEnter the data: ");
scanf("%d", &temp->data);
temp->lchild = NULL;
temp->rchild = NULL;
return temp;
}
node *create() {
char ch;
node *root = NULL, *temp, *ptr;

do {
temp = getnode();
if (root == NULL) {
root = temp;
} else {
ptr = root;
while (ptr != NULL) {
if (temp->data < ptr->data) {
if (ptr->lchild == NULL) {
ptr->lchild = temp;
break;
} else {
ptr = ptr->lchild;
}
} else {
if (ptr->rchild == NULL) {
ptr->rchild = temp;
break;
} else {
ptr = ptr->rchild;
}
}
}
}
printf("\nDo you want to add more nodes (Y/N): ");
scanf(" %c", &ch); // Added space before %c to ignore any newline
character
} while(ch == 'Y' || ch == 'y');

return root;
}
void postorder(node *ptr) {
if (ptr != NULL) {
postorder(ptr->lchild);
postorder(ptr->rchild);
printf(" %d", ptr->data);
}
}

void preorder(node *ptr) {


if (ptr != NULL) {
printf(" %d", ptr->data); // Added space for better formatting
preorder(ptr->lchild);
preorder(ptr->rchild);
}
}

int main() {
int ch;
node *root = NULL;

while (1) {
printf("\n1: Create a BST.");
printf("\n2: Preorder of BST.");
printf("\n3: Postorder of BST");
printf("\n4: Exit");
printf("\nEnter the Choice: ");
scanf("%d", &ch);

switch(ch) {
case 1:
root = create();
break;
case 2:
printf("Preorder Traversal:");
preorder(root);
printf("\n");
break;
case 3:
printf("Postorder Traversal:");
postorder(root);
printf("\n");
break;
case 4:
exit(0);
default:
printf("Invalid choice, please try again.\n");
}
}
return 0; // Return statement for main
}
OUTPUT:
9. Slip 7B Create SLL and count number of nodes
#include<stdio.h>
#include<stdlib.h>

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

typedef struct NODE node;


node *list=NULL,*last;
node * getnodenum (int digit) //create a node
{
node *temp;
temp=(node *)malloc(sizeof(node)); temp->data=digit;
temp->next=NULL;
return temp;
}
void createnumll(int num)
{
int rem;
node *temp; while(num>0)
{
rem=num%10;
num=num/10;
// printf("\nrem=%d num=%d",rem,num);
temp=getnodenum(rem);
if(list==NULL) list=temp;
else
{

temp->next=list; list=temp;
}
}
}
void display()
{
node *ptr;
for(ptr=list;ptr!=NULL;ptr=ptr->next) printf("%d->",ptr->data);
printf("NULL");
}
void main()
{
int num;
printf("\nEnter the No: "); scanf("%d",&num); createnumll(num);

printf("\nLinked after separating the digits of num: "); display();


}

10. Slip 8A Create BST and search value

//Slip 8A Create BST and search value


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

struct NODE {
struct NODE *lchild;
int data;
struct NODE *rchild;
};

typedef struct NODE node;

node* getnode() {
node *temp;
temp = (node *)malloc(sizeof(node));
printf("\nEnter the data: ");
scanf("%d", &temp->data);
temp->lchild = NULL;
temp->rchild = NULL;
return temp;
}

node* create() {
char ch;
node *root = NULL, *temp, *ptr;

do {
temp = getnode();
if (root == NULL) {
root = temp; // The first node becomes the root
} else {
ptr = root;
while (ptr != NULL) {
if (temp->data < ptr->data) {
if (ptr->lchild == NULL) {
ptr->lchild = temp; // Insert left
break;
} else {
ptr = ptr->lchild; // Go left
}
} else {
if (ptr->rchild == NULL) {
ptr->rchild = temp; // Insert right
break;
} else {
ptr = ptr->rchild; // Go right
}
}
}
}
printf("\nDo you want to add more nodes (Y/N): ");
scanf(" %c", &ch); // Notice the space before %c to consume newline
} while (ch == 'Y' || ch == 'y');

return root;
}

void display(node *ptr) {


if (ptr != NULL) {
display(ptr->lchild);
printf("%d ", ptr->data); // Added space for better readability
display(ptr->rchild);
}
}

int search(node *ptr, int val) {


while (ptr != NULL) {
if (ptr->data == val) return 1; // Value found
if (val < ptr->data) ptr = ptr->lchild; // Go left
else ptr = ptr->rchild; // Go right
}
return 0; // Value not found
}

int main() {
int ch, val, resp;
node *root = NULL;

while (1) {
printf("\n1: Create a BST.");
printf("\n2: Display");
printf("\n3: Search");
printf("\n4: Exit");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch (ch) {
case 1:
root = create();
break;
case 2:
printf("BST Elements: ");
display(root);
printf("\n");
break;
case 3:
printf("\nEnter the value to search: ");
scanf("%d", &val);
resp = search(root, val);

if (resp == 1)
printf("\nValue is found in the Tree.");
else
printf("\nValue not found in the Tree.");
break;
case 4:
exit(0);
default:
printf("\nInvalid choice. Please try again.");
}
}

return 0; // Return statement for main function


}
OUTPUT:

11. Write a menu driven program using ‘C’ for singly linked list-
- To create linked list.
- To display linked list
- To search node in linked list.
- Insert at last position
Code:
#include<stdio.h>
#include<stdlib.h>

// Structure definition for a linked list node


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

typedef struct NODE node;

node *list = NULL; // Head of the linked list


// Function to create a new node
node* createNode(int value) {
node *newNode = (node*)malloc(sizeof(node));
if(newNode == NULL) {
printf("Memory allocation failed!\n");
exit(1);
}
newNode->data = value;
newNode->next = NULL;
return newNode;
}

// Function to create a linked list


void createLinkedList() {
int value;
printf("Enter value to insert: ");
scanf("%d", &value);

node *newNode = createNode(value);


if(list == NULL) {
list = newNode; // Initialize list if it's empty
} else {
node *temp = list;
while(temp->next != NULL) {
temp = temp->next; // Traverse to the end of the list
}
temp->next = newNode; // Insert the new node at the end
}
printf("Node added successfully.\n");
}

// Function to display the linked list


void displayLinkedList() {
if(list == NULL) {
printf("Linked list is empty.\n");
return;
}

node *temp = list;


printf("Linked List: ");
while(temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}

// Function to search for a node in the linked list


void searchNode() {
if(list == NULL) {
printf("Linked list is empty.\n");
return;
}

int value, found = 0;


printf("Enter value to search: ");
scanf("%d", &value);

node *temp = list;


int position = 1;
while(temp != NULL) {
if(temp->data == value) {
printf("Node with value %d found at position %d.\n", value,
position);
found = 1;
break;
}
temp = temp->next;
position++;
}
if(!found) {
printf("Node with value %d not found.\n", value);
}
}

// Function to insert a node at the last position


void insertAtLast() {
int value;
printf("Enter value to insert at last: ");
scanf("%d", &value);

node *newNode = createNode(value);

if(list == NULL) {
list = newNode; // If list is empty, make the new node the head
} else {
node *temp = list;
while(temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode; // Insert the node at the end of the list
}

printf("Node inserted at last position.\n");


}

// Function to display the menu and get user choice


int menu() {
int choice;
printf("\n--- Menu ---\n");
printf("1. Create Linked List\n");
printf("2. Display Linked List\n");
printf("3. Search Node in Linked List\n");
printf("4. Insert Node at Last Position\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
return choice;
}

int main() {
int choice;

do {
choice = menu();
switch(choice) {
case 1:
createLinkedList();
break;
case 2:
displayLinkedList();
break;
case 3:
searchNode();
break;
case 4:
insertAtLast();
break;
case 5:
printf("Exiting...\n");
break;
default:
printf("Invalid choice! Please try again.\n");
}
} while(choice != 5);

return 0;
}
OUTPUT:

12. Write a menu driven program using ‘C’ for Dynamic implementation
of Queue for
integers. The menu includes
- Insert
- Delete
- Display
- Exit
CODE:
#include<stdio.h>
#include<stdlib.h>

// Structure definition for a queue node


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

typedef struct NODE node;

node *front = NULL; // Front pointer of the queue


node *rear = NULL; // Rear pointer of the queue

// Function to create a new node


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

// Function to insert an element into the queue


void insert() {
int value;
printf("Enter the value to insert: ");
scanf("%d", &value);

node *newNode = createNode(value);

if(rear == NULL) { // If queue is empty, both front and rear point to the
new node
front = rear = newNode;
} else {
rear->next = newNode; // Link the new node to the end of the queue
rear = newNode; // Update rear to point to the last node
}
printf("Value inserted.\n");
}

// Function to delete an element from the queue


void delete() {
if(front == NULL) {
printf("Queue is empty, nothing to delete.\n");
return;
}

node *temp = front;


front = front->next; // Move front to the next node

if(front == NULL) { // If queue becomes empty, set rear to NULL


rear = NULL;
}

printf("Deleted value: %d\n", temp->data);


free(temp); // Free the memory of the deleted node
}

// Function to display the elements of the queue


void display() {
if(front == NULL) {
printf("Queue is empty.\n");
return;
}

node *temp = front;


printf("Queue elements: ");
while(temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
// Function to display the menu and get user choice
int menu() {
int choice;
printf("\n--- Menu ---\n");
printf("1. Insert\n");
printf("2. Delete\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
return choice;
}

// Main function
int main() {
int choice;

do {
choice = menu();
switch(choice) {
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
printf("Exiting...\n");
break;
default:
printf("Invalid choice! Please try again.\n");
}
} while(choice != 4);
return 0;
}

OUTPUT:

13. Write a ‘C’ program to accept and sort n elements in ascending


order using Selection sort method.
#include <stdio.h>

// Function to perform Selection Sort


void selectionSort(int arr[], int n) {
int i, j, min_idx, temp;

// Traverse through all array elements


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
if (min_idx != i) {
temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
}
}

// Function to print the array


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

// Main function
int main() {
int n, i;

// Input number of elements


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

int arr[n]; // Declare an array of size n

// Input elements into the array


printf("Enter %d elements: \n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Sorting the array using Selection Sort


selectionSort(arr, n);
// Display the sorted array
printf("Sorted array in ascending order: \n");
printArray(arr, n);

return 0;
}
OUTPUT:

14. Write a ‘C’ program to create doubly link list and display nodes
having odd value:
#include <stdio.h>
#include <stdlib.h>

// Structure for a doubly linked list node


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

typedef struct NODE node;

node *head = NULL; // Head pointer for the doubly linked list

// Function to create a new node


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

// Function to insert a node at the end of the doubly linked list


void insertNode(int value) {
node *newNode = createNode(value);

if(head == NULL) {
head = newNode; // If the list is empty, newNode becomes the head
} else {
node *temp = head;
while(temp->next != NULL) {
temp = temp->next; // Traverse to the end of the list
}
temp->next = newNode; // Insert at the end
newNode->prev = temp; // Set the previous pointer
}
}

// Function to display nodes with odd values


void displayOddNodes() {
if(head == NULL) {
printf("The list is empty.\n");
return;
}

node *temp = head;


int foundOdd = 0;
printf("Nodes with odd values: ");
while(temp != NULL) {
if(temp->data % 2 != 0) { // Check if the value is odd
printf("%d ", temp->data);
foundOdd = 1;
}
temp = temp->next;
}

if(!foundOdd) {
printf("No odd values found.");
}
printf("\n");
}

// Function to display all nodes in the list


void displayList() {
if(head == NULL) {
printf("The list is empty.\n");
return;
}

node *temp = head;


printf("Doubly Linked List: ");
while(temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}

// Main function
int main() {
int n, i, value;

// Input the number of nodes


printf("Enter the number of elements in the list: ");
scanf("%d", &n);
// Input values and create the doubly linked list
for(i = 0; i < n; i++) {
printf("Enter element %d: ", i+1);
scanf("%d", &value);
insertNode(value);
}

// Display the entire list


displayList();

// Display nodes with odd values


displayOddNodes();

return 0;
}

15. Write menu driven program using ‘C’ for Dynamic implementation
of Stack. The
menu includes following operations:
- Push
- Pop
- Display
- Exit
#include <stdio.h>
#include <stdlib.h>

// Structure for a stack node


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

typedef struct NODE node;

node *top = NULL; // Initialize the top of the stack to NULL

// Function to create a new node


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

// Function to push an element onto the stack


void push() {
int value;
printf("Enter the value to push: ");
scanf("%d", &value);

node *newNode = createNode(value);

if(top == NULL) { // If the stack is empty, the new node becomes the top
top = newNode;
} else {
newNode->next = top; // Link the new node to the top
top = newNode; // Update top to the new node
}
printf("Value pushed onto the stack.\n");
}

// Function to pop an element from the stack


void pop() {
if(top == NULL) {
printf("Stack is empty, nothing to pop.\n");
return;
}

node *temp = top;


top = top->next; // Move the top pointer to the next node

printf("Popped value: %d\n", temp->data);


free(temp); // Free the memory of the popped node
}

// Function to display the elements of the stack


void display() {
if(top == NULL) {
printf("Stack is empty.\n");
return;
}

node *temp = top;


printf("Stack elements: ");
while(temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}

// Function to display the menu and get the user's choice


int menu() {
int choice;
printf("\n--- Menu ---\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
return choice;
}

// Main function
int main() {
int choice;

do {
choice = menu();
switch(choice) {
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
printf("Exiting...\n");
break;
default:
printf("Invalid choice! Please try again.\n");
}
} while(choice != 4);

return 0;
}
OUTPUT:

16. Write a ‘C’ program to create a singly linked list, reverse it and
display both the list.
#include <stdio.h>
#include <stdlib.h>

// Structure for a singly linked list node


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

typedef struct NODE node;

node *head = NULL; // Initialize head pointer for the list

// Function to create a new node


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

// Function to insert a node at the end of the list


void insertNode(int value) {
node *newNode = createNode(value);

if (head == NULL) { // If the list is empty, the new node becomes the
head
head = newNode;
} else {
node *temp = head;
while (temp->next != NULL) {
temp = temp->next; // Traverse to the last node
}
temp->next = newNode; // Insert the new node at the end
}
}

// Function to display the list


void displayList(node *listHead) {
if (listHead == NULL) {
printf("The list is empty.\n");
return;
}

node *temp = listHead;


while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}

// Function to reverse the linked list


node* reverseList(node *listHead) {
node *prev = NULL, *current = listHead, *next = NULL;

while (current != NULL) {


next = current->next; // Store the next node
current->next = prev; // Reverse the current node's pointer
prev = current; // Move pointers one position ahead
current = next;
}
return prev; // Return the new head (previously the last node)
}

// Main function
int main() {
int n, i, value;

// Input number of nodes


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

// Input values and create the linked list


for (i = 0; i < n; i++) {
printf("Enter element %d: ", i+1);
scanf("%d", &value);
insertNode(value);
}

// Display the original list


printf("Original List: ");
displayList(head);

// Reverse the list and display it


node *reversedHead = reverseList(head);
printf("Reversed List: ");
displayList(reversedHead);

return 0;
}

You might also like