DS PracticalSlipsSolution
DS PracticalSlipsSolution
#include <stdio.h>
#include <stdlib.h>
struct BST
{
int data;
struct BST *left;
struct BST *right;
};
if (node == NULL)
{
NODE *temp;
temp= (NODE*)malloc(sizeof(NODE));
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
if(node != NULL)
{
inorder(node->left);
printf("%d\t", node->data);
inorder(node->right);
}
}
if(node != NULL)
{
printf("%d\t", node->data);
preorder(node->left);
preorder(node->right);
}
}
if(node != NULL)
{
postorder(node->left);
postorder(node->right);
printf("%d\t", node->data);
}
}
int main()
{
int data, ch, i, n;
NODE *root=NULL;
while (ch!=5)
{
printf("\n\n1.Insertion in Binary Search Tree");
printf("\n2.Inorder");
printf("\n3.Preorder");
printf("\n4.Postorder");
printf("\n5.Exit\n");
printf("\nEnter your Choice: ");
scanf("%d", &ch);
switch (ch)
{
case 1: printf("\nEnter size of tree: " );
scanf("%d", &n);
printf("\nEnter the elements of tree)\n");
case 5: exit(0);
}
}
}
#include <stdio.h>
#include <math.h>
int main ()
{
int array[30], degree, x, count, result, i;
3) Write a ‘C’ program to accept a string from user and reverse it using
Static implementation of Stack.
#include <stdio.h>
#include <string.h>
#define max 50
int top,stack[max];
void pop(){
// Pop (Removing element from stack)
printf("%c",stack[top--]);
}
main()
{
char str[]="India";
int len = strlen(str);
int i;
for(i=0;i<len;i++)
push(str[i]);
for(i=0;i<len;i++)
pop();
}
4) Write a ‘C’ program to create Circularly Doubly Linked list and display
it
#include <stdio.h>
#include <stdlib.h>
struct node {
int num;
struct node * nextptr;
}*stnode;
int main()
{
int n;
stnode = NULL;
printf("\n\n Circular Linked List : Create and display a circular linked list
:\n");
printf("-----------------------------------------------------------------------\n");
ClListcreation(n);
displayClList();
return 0;
}
void ClListcreation(int n)
{
int i, num;
struct node *preptr, *newnode;
if(n >= 1)
{
stnode = (struct node *)malloc(sizeof(struct node));
void displayClList()
{
struct node *tmp;
int n = 1;
if(stnode == NULL)
{
printf(" No data found in the List yet.");
}
else
{
tmp = stnode;
printf("\n\n Data entered in the list are :\n");
do {
printf(" Data %d = %d\n", n, tmp->num);
tmp = tmp->nextptr;
n++;
}while(tmp != stnode);
}
}
5)Write a program to create two singly linked list of elements of type integer
and find the union of the linked lists. (Accept elements in the sorted order)
#include<stdio.h>
struct node
{
int data;
struct node *next;
};
typedef struct node NODE;
NODE *alloc(int);
NODE *create();
NODE *findlast(NODE *);
NODE *unionlist(NODE *,NODE *);
NODE *search(NODE *,int);
void display(NODE *);
NODE *getnode();
void main()
{
NODE *list1=NULL,*list2=NULL,*list3=NULL;
clrscr();
printf(“\nCreate first list.”);
list1=create();
printf(“\nCreate second list.”);
list2=create();
printf(“\n Data in first list: “);
display(list1);
printf(“\n Data in second list: “);
display(list2);
printf(“\n\n Union of two list is: “);
list3=unionlist(list1,list2);
if(list3==NULL)
printf(“\nList of union is empty”);
else
display(list3);
getch();
}
NODE *alloc(int val)
{
NODE *temp;
temp=(NODE *)malloc(sizeof(NODE));
temp->data=val;
temp->next=NULL;
return temp;
}
NODE *getnode()
{
NODE *temp;
temp=(NODE *)malloc(sizeof(NODE));
printf(“\nEnter the data: “);
scanf(“%d”,&temp->data);
temp->next=NULL;
return temp;
}
NODE *search(NODE *list,int val)
{
NODE *ptr;
for(ptr=list;ptr!=NULL && ptr->data!=val;ptr=ptr->next);
return(ptr);
}
NODE *create()
{
NODE *ptr,*temp,*list=NULL;
int n,i;
printf(“\n Enter how many nodes : “);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
temp=getnode();
if(list==NULL)
{
list=temp;
}
else
{
ptr=findlast(list);
ptr->next=temp;
}
}
return(list);
}
NODE *findlast(NODE *list)
{
NODE *ptr;
for(ptr=list;ptr->next!=NULL;ptr=ptr->next);
return(ptr);
}
NODE *unionlist(NODE *list1,NODE *list2)
{
NODE *temp,*ptr1,*ptr2,*list3=NULL;
int i,val;
for(ptr1=list1;ptr1!=NULL;ptr1=ptr1->next)
{
temp=alloc(ptr1->data);
if(list3==NULL)
list3=temp;
else
{
ptr2=findlast(list3);
ptr2->next=temp;
}
}
for(ptr1=list2;ptr1!=NULL;ptr1=ptr1->next)
{
ptr2=search(list1,ptr1->data);
if(ptr2==NULL)
{
temp=alloc(ptr1->data);
ptr2=findlast(list3);
ptr2->next=temp;
}
}
return(list3);
}
void display(NODE *list)
{
NODE *ptr;
for(ptr=list;ptr!=NULL;ptr=ptr->next)
printf(“%d->”,ptr->data);
printf(“NULL”);
}
6) Write a ‘C’ program to read the adjacency matrix of directed graph and
convert it into an adjacency list.
#include <stdio.h>
// N vertices and M Edges
int N, M;
// Update value to 1
Adj[x][y] = 1;
Adj[y][x] = 1;
}
}
// Driver Code
int main()
{
// Number of vertices
N = 5;
// Given Edges
int arr[][2]
= { { 1, 2 }, { 2, 3 },
{ 4, 5 }, { 1, 5 } };
// Number of Edges
M = sizeof(arr) / sizeof(arr[0]);
return 0;
}
7)Write menu driven program using ‘C’ for Binary Search Tree. The
menu includes
- Create a Binary Search Tree
- Traverse it by using Inorder and Postorder traversing technique
#include <stdio.h>
#include <stdlib.h>
struct BST
{
int data;
struct BST *left;
struct BST *right;
};
if (node == NULL)
{
NODE *temp;
temp= (NODE*)malloc(sizeof(NODE));
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
return node;
if(node != NULL)
{
printf("%d\t", node->data);
preorder(node->left);
preorder(node->right);
}
}
if(node != NULL)
{
postorder(node->left);
postorder(node->right);
printf("%d\t", node->data);
}
}
int main()
{
int data, ch, i, n;
NODE *root=NULL;
while (ch!=5)
{
printf("\n\n1.Insertion in Binary Search Tree");
printf("\n2.Inorder");
printf("\n3.Preorder");
printf("\n4.Postorder");
printf("\n5.Exit\n");
printf("\nEnter your Choice: ");
scanf("%d", &ch);
switch (ch)
{
case 1: printf("\nEnter size of tree: " );
scanf("%d", &n);
printf("\nEnter the elements of tree)\n");
case 5: exit(0);
}
}
}
8)Write a ‘C’ program to create a singly linked list and count total number
of nodes in it and display the list and total number of Nodes.
#include <stdio.h>
#include <stdlib.h>
// Structure for a node in a linked list
struct node {
int num; // Data of the node
struct node *nextptr; // Address of the next node
} *stnode; // Pointer to the starting node
// Function prototypes
void createNodeList(int n); // Function to create the linked list
int NodeCount(); // Function to count the nodes
void displayList(); // Function to display the linked list
// Main function
int main() {
int n, totalNode;
return 0;
}
9) Write a ‘C’ program to accept and sort n elements in ascending order by using
bubble sort.
#include <stdio.h>
#define MAXSIZE 10
void main()
{
int array[MAXSIZE];
int i, j, num, temp;
10) Write a ‘C’ program to accept and sort n elements in ascending order
by using insertion sort.
#include <stdio.h>
int main(void)
{
int n, i, j, temp;
int arr[64];
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
for (i = 1; i < n; i++)
{
j = i;
while (j > 0 && arr[j - 1] > arr[j])
{
temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
j--;
}
}
printf("Sorted list in ascending order:\n");
for (i = 0; i < n; i++)
{
printf("%d\n", arr[i]);
}
return 0;
}
#include<stdio.h>
int stack[20];
int top = -1;
void push(int x)
{
stack[++top] = x;
}
int pop()
{
return stack[top--];
}
int main()
{
char exp[20];
char *e;
int n1,n2,n3,num;
printf("Enter the expression :: ");
scanf("%s",exp);
e = exp;
while(*e != '\0')
{
if(isdigit(*e))
{
num = *e - 48;
push(num);
}
else
{
n1 = pop();
n2 = pop();
switch(*e)
{
case '+':
{
n3 = n1 + n2;
break;
}
case '-':
{
n3 = n2 - n1;
break;
}
case '*':
{
n3 = n1 * n2;
break;
}
case '/':
{
n3 = n2 / n1;
break;
}
}
push(n3);
}
e++;
}
printf("\nThe result of expression %s = %d\n\n",exp,pop());
return 0;
}
12) Write a ‘C’ program to create a singly linked list, reverse it and
display both the list.
#include <stdio.h>
#include <stdlib.h>
// Function prototypes
void createNodeList(int n); // Function to create the linked list
void reverseDispList(); // Function to reverse the linked list
void displayList(); // Function to display the linked list
// Main function
int main() {
int n;
if(stnode != NULL) {
prevNode = stnode;
curNode = stnode->nextptr;
stnode = stnode->nextptr;
while(stnode != NULL) {
stnode = stnode->nextptr;
curNode->nextptr = prevNode;
prevNode = curNode;
curNode = stnode;
}
stnode = prevNode; // Convert the last node as head
}
}
14) Write a ‘C’ program to sort randomly generated array elements using
Insertion sort method. (Use Random Function)
#include <math.h>
#include <stdio.h>
int main() {
int arr[] = { 12, 11, 13, 5, 6 };
int N = sizeof(arr) / sizeof(arr[0]);
return 0;
}
15) 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
#include <stdio.h>
#include <stdlib.h>
// List is empty
if (start == NULL)
printf("\nList is empty\n");
// Changes links
temp->link = 0;
temp->info = data;
head = start;
while (head->link != NULL) {
head = head->link;
}
head->link = temp;
}
// Change Links
temp = start;
newnode->info = data;
newnode->link = 0;
while (i < pos - 1) {
temp = temp->link;
i++;
}
newnode->link = temp->link;
temp->link = newnode;
}
// If LL is empty
if (start == NULL)
printf("\nList is empty\n");
// Otherwise
else {
printf("\nEnter index : ");
// Position to be deleted
scanf("%d", &pos);
position = malloc(sizeof(struct node));
temp = start;
// Change Links
position = temp->link;
temp->link = position->link;
// Free memory
free(position);
}
}
// If LL is empty
if (start == NULL)
printf("\nList is empty\n");
// Otherwise
else {
temp = start;
int max = temp->info;
// If LL is empty
if (start == NULL)
printf("\nList is empty\n");
// Otherwise
else {
temp = start;
// Traverse the LL
while (temp != NULL) {
// If LL is empty
if (start == NULL) {
return;
}
// Else
else {
// Traverse the LL
while (current != NULL) {
index = current->link;
// If LL is empty
if (start == NULL)
printf("List is empty\n");
// Else
else {
// Traverse the LL
while (start != NULL) {
// reversing of points
t2 = start->link;
start->link = t1;
t1 = start;
start = t2;
}
start = t1;
// Print the LL
while (temp != NULL) {
printf("%d ", temp->info);
temp = temp->link;
}
}
}
// checking by traversing
while (tr != NULL) {
// checking for key
if (tr->info == key) {
found = 1;
break;
}
// moving forward if not at this position
else {
tr = tr->link;
}
}
// Driver Code
int main()
{
createList();
int choice;
while (1) {
switch (choice) {
case 1:
traverse();
break;
case 2:
insertAtFront();
break;
case 3:
insertAtEnd();
break;
case 4:
insertAtPosition();
break;
case 5:
deleteFirst();
break;
case 6:
deleteEnd();
break;
case 7:
deletePosition();
break;
case 8:
maximum();
break;
case 9:
mean();
break;
case 10:
sort();
break;
case 11:
reverseLL();
break;
case 12:
search();
break;
case 13:
exit(1);
break;
default:
printf("Incorrect Choice\n");
}
}
return 0;
}
16) Write a menu driven program using ‘C’ for Dynamic implementation
of Queue for integers. The menu includes
- Insert
- Delete
- Display
- Exit
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
struct node
{
int data;
struct node *link;
}*front, *rear;
// function protypes
void insert();
void delete();
void queue_size();
void check();
void first_element();
void main()
{
int choice, value;
while(1)
{
printf("enter the choice \n");
printf("1 : create an empty queue \n2 : Insert element\n");
printf("3 : Dequeue an element \n4 : Check if empty\n");
printf("5. Get the first element of the queue\n");
printf("6. Get the number of entries in the queue\n");
printf("7. Exit\n");
scanf("%d", &choice);
switch (choice) // menu driven program
{
case 1:
printf("Empty queue is created with a capacity of %d\n", MAX);
break;
case 2:
insert();
break;
case 3:
delete();
break;
case 4:
check();
break;
case 5:
first_element();
break;
case 6:
queue_size();
break;
case 7:
exit(0);
default:
printf("wrong choice\n");
break;
}
}
}
temp = front;
if (front == NULL)
{
printf("queue is empty \n");
front = rear = NULL;
}
else
{
printf("deleted element is %d\n", front->data);
front = front->link;
free(temp);
}
}
temp = front;
int cnt = 0;
if (front == NULL)
{
printf(" queue empty \n");
}
while (temp)
{
printf("%d ", temp->data);
temp = temp->link;
cnt++;
}
printf("********* size of queue is %d ******** \n", cnt);
}
16) Write a C program that accepts the graph as an adjacency matrix and
checks if the graph is undirected. The matrix for undirected graph is
symmetric. Also calculate in degree of all vertices
- Read a graph as adjacency Matrix
- Check the matrix is symmetric or not
- Calculate indegree of all vertices
// Update value to 1
Adj[x][y] = 1;
Adj[y][x] = 1;
}
}
// Driver Code
int main()
{
// Number of vertices
N = 5;
// Given Edges
int arr[][2]
= { { 1, 2 }, { 2, 3 },
{ 4, 5 }, { 1, 5 } };
// Number of Edges
M = sizeof(arr) / sizeof(arr[0]);
return 0;
}
17) Write a ‘C’ program to accept and sort n elements in ascending order
using Selection sort method.
#include <stdio.h>
int main() {
int arr[] = {64, 25, 12, 22, 11};
int N = sizeof(arr) / sizeof(arr[0]);
printf("Unsorted array: \n");
for (int i = 0; i < N; i++) {
printf("%d ", arr[i]);
}
printf("\n");
#include<stdio.h>
#include<ctype.h>
char stack[100];
int top = -1;
void push(char x)
{
stack[++top] = x;
}
char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
return 0;
}
int main()
{
char exp[100];
char *e, x;
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
e = exp;
while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c ",pop());
push(*e);
}
e++;
}
while(top != -1)
{
printf("%c ",pop());
}return 0;
}
19) Write a ‘C’ program to create doubly link list and display nodes having
odd value
#include <stdio.h>
#include <stdlib.h>
// Function prototypes
void DlListcreation(int n);
void displayDlList();
int main() {
int n;
stnode = NULL;
ennode = NULL;
printf("\n\n Doubly Linked List: Create and display a doubly linked list:\n");
printf("-------------------------------------------------------------------\n");
if (n >= 1) {
stnode = (struct node *)malloc(sizeof(struct node)); // Allocate memory for
the first node
if (stnode != NULL) {
printf(" Input data for node 1 : ");
scanf("%d", &num);
stnode->num = num;
stnode->preptr = NULL;
stnode->nextptr = NULL;
ennode = stnode; // Assign stnode as the last node
// Create nodes and link them to form the doubly linked list
for (i = 2; i <= n; i++) {
fnNode = (struct node *)malloc(sizeof(struct node));
if (fnNode != NULL) {
printf(" Input data for node %d : ", i);
scanf("%d", &num);
fnNode->num = num;
fnNode->preptr = ennode;
fnNode->nextptr = NULL;
ennode->nextptr = fnNode;
ennode = fnNode;
} else {
printf(" Memory can not be allocated.");
break;
}
}
} else {
printf(" Memory can not be allocated.");
}
}
}
#include <stdio.h>
#include <string.h>
#define max 50
int top,stack[max];
void pop(){
// Pop (Removing element from stack)
printf("%c",stack[top--]);
}
int main()
{
char str[]="India";
int len = strlen(str);
int i;
for(i=0;i<len;i++)
push(str[i]);
for(i=0;i<len;i++)
pop();
return 0;
}
21) Write a ‘C’ program to accept names from the user and sort in
alphabetical order using bubble sort
- Accept n name
- Bubble sort Function
- Display
#include <stdio.h>
#include <string.h>
void main()
{
printf("\n----------------------------------------\n");
printf("Input NamestSorted names\n");
printf("------------------------------------------\n");
printf("------------------------------------------\n");
#include<stdio.h>
#include<stdlib.h>
#define max_size 5
int stack[max_size],top=-1;
/*------ Function Prototype------------*/
void push();
void pop();
void peep();
void display();
/*-------------------------------------*/
int main()
{
int choice;
do
{
//printf("\n");
printf("\n\n--------STACK OPERATIONS-----------\n");
printf("1.Push\n");
printf("2.Pop\n");
printf("3.Peep\n");
printf("4.Display\n");
printf("5.Exit\n");
printf("-----------------------");
printf("\nEnter your choice:\t");
scanf("%d",&choice);
switch(choice)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
peep();
break;
case 4:
display();
break;
case 5:
exit(0);
break;
default:
printf("\nInvalid choice:\n");
break;
}
}while(choice!=5);
return 0;
}
void push() //Inserting element in to the stack
{
int item;
if(top==(max_size-1))
{
printf("\nStack Overflow:");
}
else
{
printf("Enter the element to be inserted:\t");
scanf("%d",&item);
top=top+1;
stack[top]=item;
}
}
void pop() //deleting an element from the stack
{
int item;
if(top==-1)
{
printf("Stack Underflow:");
}
else
{
item=stack[top];
top=top-1;
printf("\nThe poped element: %d\t",item);
}
}
void peep()
{
if(top==-1)
{
printf("\nStack is empty:");
}
else
{
printf("The topmost element of the stack is %d",stack[top]);
}
}
void display()
{
int i;
if(top==-1)
{
printf("\nStack is Empty:");
}
else
{
printf("\nThe stack elements are:\n" );
for(i=top;i>=0;i--)
{
printf("%d\n",stack[i]);
}
}
}
23) Write a ‘C’ program to create to a Singly linked list. Accept the
number from user, search the number in the list.If the number is present
display the Position of node .If number not present print the message
“Number not Found”.
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node * next;
};
struct node* head=NULL;
}
if(flag==0)
{
printf("Elemet not found.\n");
}
else
{
printf("Element found at position :%d",i);
}
}
void main()
{
int n,key;
printf("Enter size of Linked list :\n");
scanf("%d",&n);
createnode(n);
printf("\n\nLinked List :\n");
display();
printf("\nEnter element you want to search :\n");
scanf("%d",&key);
search(key);
}
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
// Stack implementation
int stack[MAX_SIZE];
int top = -1;
void push(int item) {
if (top >= MAX_SIZE - 1) {
printf("Stack Overflow\n");
return;
}
top++;
stack[top] = item;
}
int pop() {
if (top < 0) {
printf("Stack Underflow\n");
return -1;
}
int item = stack[top];
top--;
return item;
}
int is_operator(char symbol) {
if (symbol == '+' || symbol == '-' || symbol == '*' || symbol == '/') {
return 1;
}
return 0;
}
int evaluate(char* expression) {
int i = 0;
char symbol = expression[i];
int operand1, operand2, result;
int main() {
char expression[] = "5 6 7 + * 8 -";
int result = evaluate(expression);
printf("Result= %d\n", result);
return 0;
}
25) Write a ‘C’ program to accept the names of cities and store them in
array. Accept the city name from user and use linear search algorithm to
check whether the city is present in array or not.
#include<stdio.h>
#include<string.h>
typedef struct city
{
char name[30];
int code;
}record;
record city[100];
int read_file(record *a)
{
int i=0;
FILE *fp;
if((fp=fopen("sortedcities.txt","r"))!=NULL)
while(!feof(fp))
{
fscanf(fp,"%s%d",a[i].name,&a[i].code);
i++;
}
return (i-1);
}
void write_file(record *a,int n)
{
int i=0;
FILE *fp;
if((fp=fopen("sorted_cities.txt","w"))!=NULL)
for(i=0;i<n;i++)
fprintf(fp,"\n%s\t%d",a[i].name,a[i].code);
}
void sort(record *a,int n)
{
int i,j;
record t;
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if(strcmp(a[j].name,a[j+1].name)>0)
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
}
int read_file1(record *a)
{
int i=0;
FILE *fp;
if((fp=fopen("sorted_cities.txt","r"))!=NULL)
while(!feof(fp))
{
fscanf(fp,"%s%d",a[i].name,&a[i].code);
i++;
}
return (i-1);
}
void b_search(record *a,int n,char key[20])
{
int l,h,mid;
l=0;
h=n-1;
while(h>=l)
{
mid=(l+h)/2;
if(strcmp(key,a[mid].name)==0)
{
printf("\nSTD code:%d\n ",a[mid].code);
break;
}
else if(strcmp(key,a[mid].name)<0)
h=mid-1;
else
l=mid+1;
}
if(h<l)
printf("\ncity not in list\n");
}
int main()
{
char key[20];
int n,m;
n=read_file(city);
sort(city,n);
write_file(city,n);
printf("\nenter city name\n");
scanf("%s",key);
b_search(city,n,key);
return 0;
}
26) Write a ‘C’ program to read ‘n’ integers and store them in a binary
Search tree structure and count the following and display it.
- Number of nodes
- Degree of tree
- Leaf nodes
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *left, *right;
};
struct node *createnode(int key)
{
struct node *newnode = (struct node*)malloc(sizeof(struct node));
newnode->info = key;
newnode->left = NULL;
newnode->right = NULL;
return(newnode);
}
static int count = 0;
int countnodes(struct node *root)
{
if(root != NULL)
{
countnodes(root->left);
count++;
countnodes(root->right);
}
return count;
}
/*
* Main Function
*/
int main()
{
/* Creating first Tree. */
struct node *newnode = createnode(25);
newnode->left = createnode(27);
newnode->right = createnode(19);
newnode->left->left = createnode(17);
newnode->left->right = createnode(91);
newnode->right->left = createnode(13);
newnode->right->right = createnode(55);
/* Sample Tree 1:
* 25
* / \
* 27 19
* /\ /\
* 17 91 13 55
*/
printf("Number of nodes in tree 1 = %d ",countnodes(newnode));
printf("\n");
count = 0;
#include <stdio.h>
#include <stdlib.h>
// merge function
void Merge(int arr[], int left, int mid, int right)
{
int i, j, k;
int size1 = mid - left + 1;
int size2 = right - mid;
// driver code
int main()
{
int size;
printf("Enter the size: ");
scanf("%d", &size);
int arr[size];
printf("Enter the elements of array: ");
for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
28) Write a ‘C’ program to create a singly Link list and display its
alternative nodes. (start displaying from first node)
#include <stdio.h>
#include <stdlib.h>
struct node
{
int a;
struct node *next;
};
int main()
{
struct node *head = NULL;
generate(&head);
printf("\nDisplaying the alternate nodes\n");
display(head);
delete(&head);
return 0;
}
29) Write a ‘C’ program which accept the string and check whether the
string is Palindrome or not using stack. (Use Static/Dynamic
implementation of Stack)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 50
int top = -1, front = 0;
int stack[MAX];
void push(char);
void pop();
/* push a character into stack */
void push(char a)
{
top++;
stack[top] = a;
}
/* delete an element in stack */
void pop()
{
top--;
}
int main()
{
int i, cho;
char s[MAX], b;
printf("\tMENU");
printf("\n---------------------------\n");
printf("1.Check string is palindrome.\n2.Exit\n");
printf("---------------------------\n");
while (1)
{
printf("Choose operation : ");
scanf("%d", &cho);
switch (cho)
{
case 1:
printf("\nEnter string : ");
scanf("%s", s);
for (i = 0;s[i] != '\0';i++)
{
b = s[i];
push(b);
}
for (i = 0;i < (strlen(s) / 2);i++)
{
if (stack[top] == stack[front])
{
pop();
front++;
}
else
{
printf("'%s' is not palindrome.\n\n", s);
break;
}
}
if ((strlen(s) / 2)== front)
printf("'%s' is palindrome.\n\n", s);
front = 0;
top = -1;
break;
case 2:
exit(0);
default: printf("Invalid operation \n");
}
}
return 0;
}
30) Write a ‘C’ program to swap mth and nth element of singly linked list
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
int data;
struct node *link;
}*head,*q,*temp,*t;
int cnt,num1,num2,m,n;
void create();
void display();
void swap();
int count();
void main()
{
int ch='y';
clrscr();
while(ch=='y'||ch=='Y')
{
create();
printf("\nWant to add another node(Y|N): ");
scanf("%s",&ch);
}
display();
swap();
count();
display();
getch();
}
void create()
{
temp=malloc(sizeof(struct node));
printf("\nEnter the elements for singly linked list: ");
scanf("%d",&temp->data);
temp->link=NULL;
if(head==NULL)
head=temp;
else
{
q=head;
while(q->link!=NULL)
{
q=q->link;
}
q->link=temp;
}
}
void display()
{
if(head==NULL)
printf("\nlinked list is empty");
else
{
printf("\nElement in singly linked list are: \n");
q=head;
while(q!=NULL)
{
printf("%d\n",q->data);
q=q->link;
}
}
}
void swap()
{
int i;
printf("\nEnter Mth and Nth position of singly linked list for swaping: ");
scanf("\n%d%d",&m,&n);
count();
if(m>0&&m<=cnt&&n>0&&n<=cnt)
{
q=head;
i=0;
printf("\n\nElement after swapping");
while(q!=NULL)
{
i++;
if(m==i)
q->data=num2;
if(n==i)
q->data=num1;
q=q->link;
}
else
printf("\nyou entered wrong position please try again");
}
int count()
{
cnt=0;
q=head;
while(q!=NULL)
{
cnt++;
if(cnt==m)
num1=q->data;
if(cnt==n)
num2=q->data;
q=q->link;
}
return cnt;
}
void bfs(int v)
{
for (i = 1; i <= n; i++)
if (adj[v][i] && !visited[i])
queue[++rear] = i;
if (front <= rear)
{
visited[queue[front]] = 1;
bfs(queue[front++]);
}
}
int main()
{
int v;
printf("Enter the number of vertices: ");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
queue[i] = 0;
visited[i] = 0;
}
printf("Enter graph data in matrix form: \n");
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
scanf("%d", &adj[i][j]);
printf("Enter the starting vertex: ");
scanf("%d", &v);
bfs(v);
printf("The node which are reachable are: \n");
for (i = 1; i <= n; i++)
if (visited[i])
printf("%d\t", i);
else
printf("BFS is not possible. Not all nodes are reachable");
return 0;
}
32) Write a ‘C’ program Accept n elements from user store it in an array.
Accept a value from the user and use linear/Sequential search method to
check whether the value is present in array or not. Display proper message.
#include <stdio.h>
int main() {
int arr[] = { 10, 50, 30, 70, 80, 60, 20, 90, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int key = 30;
return 0;
}
33) Write a ‘C’ program which accept an Expression and check whether
the expression is Parenthesized or not using stack. (Use Static/Dynamic
implementation of Stack).
#include<stdio.h>
int main()
{
char expression[50]; // declaration of char type array
int x=0, i=0; // declaration of two integer type variables
printf("\nEnter an expression");
scanf("%s", expression);
// Scanning the expression until we reach the end of the expression.
while(expression[i]!= '\0')
{
// Condition to check the symbol is '('
if(expression[i]=='(')
{
x++; // incrementing 'x' variable
}
// condition to check the symbol is ')'
else if(expression[i]==')')
{
x--; // decrementing 'x' variable
if(x<0)
break;
}
i++; // incrementing 'i' variable.
}
// Condition to check whether x is equal to 0 or not.
if(x==0)
{
printf("Expression is balanced");
}
else
{
printf("Expression is unbalanced");
}
return 0;
}
34) Write a ‘C’ program to remove last node of the singly linked list and
insert it at the beginning of list.
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node *next;
};
int main ()
{
//creating 4 pointers of type struct Node
//So these can point to address of struct type variable
struct Node *head = NULL;
struct Node *node2 = NULL;
struct Node *node3 = NULL;
struct Node *node4 = NULL;
struct Node *node5 = NULL;
struct Node *node6 = NULL;
node3->data = 6;
node3->next = node4;
node4->data = 8;
node4->next = node5;
node5->data = 10;
node5->next = node6;
node6->data = 12;
node6->next = NULL;
deleteEnd (&head);
deleteEnd (&head);
return 0;
}
#include <stdio.h>
#define SIZE 5
int items[SIZE];
int front = -1, rear = -1;
// adding an element
void enQueue(int element) {
if (isFull())
printf("\n Queue is full!! \n");
else {
if (front == -1) front = 0;
rear = (rear + 1) % SIZE;
items[rear] = element;
printf("\n Inserted -> %d", element);
}
}
// removing an element
int deQueue() {
int element;
if (isEmpty()) {
printf("\n Queue is empty !! \n");
return (-1);
} else {
element = items[front];
if (front == rear) {
front = -1;
rear = -1;
}
// Q has only one element, so we reset the
// queue after dequeing it. ?
else {
front = (front + 1) % SIZE;
}
printf("\n Deleted element -> %d \n", element);
return (element);
}
}
// display the queue
void display() {
int i;
if (isEmpty())
printf(" \n Empty Queue\n");
else {
printf("\n Front -> %d ", front);
printf("\n Items -> ");
for (i = front; i != rear; i = (i + 1) % SIZE) {
printf("%d ", items[i]);
}
printf("%d ", items[i]);
printf("\n Rear -> %d \n", rear);
}
}
int main() {
// fails because front = -1
deQueue();
enQueue(1);
enQueue(2);
enQueue(3);
enQueue(4);
enQueue(5);
display();
deQueue();
display();
enQueue(7);
display();
return 0;
}
36) Write a ‘C’ program to create Doubly Link list and display it.
#include <stdio.h>
#include <stdlib.h>
// Function prototypes
void DlListcreation(int n);
void displayDlList();
int main() {
int n;
stnode = NULL;
ennode = NULL;
printf("\n\n Doubly Linked List: Create and display a doubly linked list:\n");
printf("-------------------------------------------------------------------\n");
if (n >= 1) {
stnode = (struct node *)malloc(sizeof(struct node)); // Allocate memory for
the first node
if (stnode != NULL) {
printf(" Input data for node 1 : ");
scanf("%d", &num);
stnode->num = num;
stnode->preptr = NULL;
stnode->nextptr = NULL;
ennode = stnode; // Assign stnode as the last node
// Create nodes and link them to form the doubly linked list
for (i = 2; i <= n; i++) {
fnNode = (struct node *)malloc(sizeof(struct node));
if (fnNode != NULL) {
printf(" Input data for node %d : ", i);
scanf("%d", &num);
fnNode->num = num;
fnNode->preptr = ennode;
fnNode->nextptr = NULL;
ennode->nextptr = fnNode;
ennode = fnNode;
} else {
printf(" Memory can not be allocated.");
break;
}
}
} else {
printf(" Memory can not be allocated.");
}
}
}
37) Write a ‘C’ program to read n integers and create two lists such that all
positive numbers are in one list and negative numbers are in another list.
Display both the lists.
#include <stdio.h>
printf("Array: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Driver program
int main()
{
int arr[] = { 2, -1, 5, 6, 0, -3 };
int n;
n = sizeof(arr) / sizeof(arr[0]);
printArray(arr, n);
return 0;
}