0% found this document useful (0 votes)
111 views36 pages

DS LAb Manual

The document contains code for various operations on linked lists and queues. It includes code to insert elements into singly linked lists, circular queues, and linear queues. It also includes code to delete elements from these data structures. Additionally, it includes a problem to add two polynomials represented as linked lists, and code for the addition operation.

Uploaded by

Gagana P
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)
111 views36 pages

DS LAb Manual

The document contains code for various operations on linked lists and queues. It includes code to insert elements into singly linked lists, circular queues, and linear queues. It also includes code to delete elements from these data structures. Additionally, it includes a problem to add two polynomials represented as linked lists, and code for the addition operation.

Uploaded by

Gagana P
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/ 36

1 , 3 , 7 , 11,14 , 17

2 . program for bubble sort

#include <stdio.h>

void bubbleSort(int arr[], int n)

int i, j, temp;

for(i = 0; i < n; i++)

for(j = 0; j < n-i-1; j++)

if( arr[j] > arr[j+1])

// swap the elements

temp = arr[j];

arr[j] = arr[j+1];

arr[j+1] = temp;

// print the sorted array

printf("Sorted Array: ");

for(i = 0; i < n; i++)

printf("%d ", arr[i]);

int main()

{
int arr[100], i, n, step, temp;

// ask user for number of elements to be sorted

printf("Enter the number of elements to be sorted: ");

scanf("%d", &n);

// input elements if the array

for(i = 0; i < n; i++)

printf("Enter element no. %d: ", i+1);

scanf("%d", &arr[i]);

// call the function bubbleSort

bubbleSort(arr, n);

return 0;

4. Write a program to insert the elements {61,16,8,27} into singly linked list and delete 8,61,27 from
the list. Display your list after each insertion and deletion.

include<stdio.h>

#include<conio.h>

#include<process.h>

struct node

int data;

struct node *next;

}*start=NULL,*q,*t;

int main()

{
int ch;

void insert_beg();

void insert_end();

int insert_pos();

void display();

void delete_beg();

void delete_end();

int delete_pos();

while(1)

printf("\n\n---- Singly Linked List(SLL) Menu ----");

printf("\n1.Insert\n2.Display\n3.Delete\n4.Exit\n\n");

printf("Enter your choice(1-4):");

scanf("%d",&ch);

switch(ch)

case 1:

printf("\n---- Insert Menu ----");

printf("\n1.Insert at beginning\n2.Insert at end\n3.Insert at specified position\n4.Exit");

printf("\n\nEnter your choice(1-4):");

scanf("%d",&ch);

switch(ch)

case 1: insert_beg();

break;

case 2: insert_end();

break;

case 3: insert_pos();
break;

case 4: exit(0);

default: printf("Wrong Choice!!");

break;

case 2: display();

break;

case 3: printf("\n---- Delete Menu ----");

printf("\n1.Delete from beginning\n2.Delete from end\n3.Delete from specified


position\n4.Exit");

printf("\n\nEnter your choice(1-4):");

scanf("%d",&ch);

switch(ch)

case 1: delete_beg();

break;

case 2: delete_end();

break;

case 3: delete_pos();

break;

case 4: exit(0);

default: printf("Wrong Choice!!");

break;

case 4: exit(0);

default: printf("Wrong Choice!!");

}
return 0;

void insert_beg()

int num;

t=(struct node*)malloc(sizeof(struct node));

printf("Enter data:");

scanf("%d",&num);

t->data=num;

if(start==NULL) //If list is empty

t->next=NULL;

start=t;

else

t->next=start;

start=t;

void insert_end()

int num;

t=(struct node*)malloc(sizeof(struct node));

printf("Enter data:");

scanf("%d",&num);

t->data=num;

t->next=NULL;
if(start==NULL) //If list is empty

start=t;

else

q=start;

while(q->next!=NULL)

q=q->next;

q->next=t;

int insert_pos()

int pos,i,num;

if(start==NULL)

printf("List is empty!!");

return 0;

t=(struct node*)malloc(sizeof(struct node));

printf("Enter data:");

scanf("%d",&num);

printf("Enter position to insert:");

scanf("%d",&pos);

t->data=num;

q=start;
for(i=1;i<pos-1;i++)

if(q->next==NULL)

printf("There are less elements!!");

return 0;

q=q->next;

t->next=q->next;

q->next=t;

return 0;

void display()

if(start==NULL)

printf("List is empty!!");

else

q=start;

printf("The linked list is:\n");

while(q!=NULL)

printf("%d->",q->data);

q=q->next;

}
}

void delete_beg()

if(start==NULL)

printf("The list is empty!!");

else

q=start;

start=start->next;

printf("Deleted element is %d",q->data);

free(q);

void delete_end()

if(start==NULL)

printf("The list is empty!!");

else

q=start;

while(q->next->next!=NULL)

q=q->next;

t=q->next;
q->next=NULL;

printf("Deleted element is %d",t->data);

free(t);

int delete_pos()

int pos,i;

if(start==NULL)

printf("List is empty!!");

return 0;

printf("Enter position to delete:");

scanf("%d",&pos);

q=start;

for(i=1;i<pos-1;i++)

if(q->next==NULL)

printf("There are less elements!!");

return 0;

q=q->next;

t=q->next;
q->next=t->next;

printf("Deleted element is %d",t->data);

free(t);

return 0;

5 . Write a program to insert the elements {61,16,8,27} into linear queue and delete three elements
from the list. Display your list after each insertion and deletion.

#include <stdio.h>

#include<stdlib.h>

#define MAX 50

void insert();

void delete();

void display();

int queue_array[MAX];

int rear = - 1;

int front = - 1;

int main()

int choice;

while (1)

printf("1.Insert element to queue n");

printf("2.Delete element from queue n");

printf("3.Display all elements of queue n");

printf("4.Quit n");

printf("Enter your choice : ");

scanf("%d", &choice);

switch(choice)

{
case 1:

insert();

break;

case 2:

delete();

break;

case 3:

display();

break;

case 4:

exit(1);

default:

printf("Wrong choice n");

void insert()

int item;

if(rear == MAX - 1)

printf("Queue Overflow n");

else

if(front== - 1)

front = 0;

printf("Inset the element in queue : ");

scanf("%d", &item);

rear = rear + 1;

queue_array[rear] = item;

}
void delete()

if(front == - 1 || front > rear)

printf("Queue Underflow n");

return;

else

printf("Element deleted from queue is : %dn", queue_array[front]);

front = front + 1;

void display()

int i;

if(front == - 1)

printf("Queue is empty n");

else

printf("Queue is : n");

for(i = front; i <= rear; i++)

printf("%d ", queue_array[i]);

printf("n");

6 . Write a program to insert the elements {61,16,8,27} into circular queue and delete 4 elements
from the list. Display your list after each insertion and deletion.

#include<stdio.h>

# define MAX 5
int cqueue_arr[MAX];

int front = -1;

int rear = -1;

void insert(int item)

if((front == 0 && rear == MAX-1) || (front == rear+1))

printf("Queue Overflow n");

return;

if(front == -1)

front = 0;

rear = 0;

else

if(rear == MAX-1)

rear = 0;

else

rear = rear+1;

cqueue_arr[rear] = item ;

void deletion()

if(front == -1)

printf("Queue Underflown");

return ;

}
printf("Element deleted from queue is : %dn",cqueue_arr[front]);

if(front == rear)

front = -1;

rear=-1;

else

if(front == MAX-1)

front = 0;

else

front = front+1;

void display()

int front_pos = front,rear_pos = rear;

if(front == -1)

printf("Queue is emptyn");

return;

printf("Queue elements :n");

if( front_pos <= rear_pos )

while(front_pos <= rear_pos)

printf("%d ",cqueue_arr[front_pos]);

front_pos++;

else

{
while(front_pos <= MAX-1)

printf("%d ",cqueue_arr[front_pos])

front_pos++;

front_pos = 0;

while(front_pos <= rear_pos)

printf("%d ",cqueue_arr[front_pos]);

front_pos++;

printf("n");

int main()

int choice,item;

do

printf("1.Insertn");

printf("2.Deleten");

printf("3.Displayn");

printf("4.Quitn");

printf("Enter your choice : ");

scanf("%d",&choice);

switch(choice)

case 1 :

printf("Input the element for insertion in queue : ");

scanf("%d", &item);

insert(item);
break;

case 2 :

deletion();

break;

case 3:

display();

break;

case 4:

break;

default:

printf("Wrong choicen");

}while(choice!=4);

return 0;

8. Write a program to add 6x3+10x2+0x+5 and 4x2+2x+1 using linked list.

/* program for addition of two polynomials

* polynomial are stored using structure

* and program uses array of structure

*/

#include<stdio.h>

/* declare structure for polynomial */

struct poly

int coeff;

int expo;

};

/* declare three arrays p1, p2, p3 of type structure poly.

* each polynomial can have maximum of ten terms


* addition result of p1 and p2 is stored in p3 */

struct poly p1[10],p2[10],p3[10];

/* function prototypes */

int readPoly(struct poly []);

int addPoly(struct poly [],struct poly [],int ,int ,struct poly []);

void displayPoly( struct poly [],int terms);

int main()

int t1,t2,t3;

/* read and display first polynomial */

t1=readPoly(p1);

printf(" \n First polynomial : ");

displayPoly(p1,t1);

/* read and display second polynomial */

t2=readPoly(p2);

printf(" \n Second polynomial : ");

displayPoly(p2,t2);

/* add two polynomials and display resultant polynomial */

t3=addPoly(p1,p2,t1,t2,p3);

printf(" \n\n Resultant polynomial after addition : ");

displayPoly(p3,t3);

printf("\n");

return 0;

}
int readPoly(struct poly p[10])

int t1,i;

printf("\n\n Enter the total number of terms in the polynomial:");

scanf("%d",&t1);

printf("\n Enter the COEFFICIENT and EXPONENT in DESCENDING ORDER\n");

for(i=0;i<t1;i++)

printf(" Enter the Coefficient(%d): ",i+1);

scanf("%d",&p[i].coeff);

printf(" Enter the exponent(%d): ",i+1);

scanf("%d",&p[i].expo); /* only statement in loop */

return(t1);

int addPoly(struct poly p1[10],struct poly p2[10],int t1,int t2,struct poly p3[10])

int i,j,k;

i=0;

j=0;

k=0;

while(i<t1 && j<t2)

if(p1[i].expo==p2[j].expo)

{
p3[k].coeff=p1[i].coeff + p2[j].coeff;

p3[k].expo=p1[i].expo;

i++;

j++;

k++;

else if(p1[i].expo>p2[j].expo)

p3[k].coeff=p1[i].coeff;

p3[k].expo=p1[i].expo;

i++;

k++;

else

p3[k].coeff=p2[j].coeff;

p3[k].expo=p2[j].expo;

j++;

k++;

/* for rest over terms of polynomial 1 */

while(i<t1)

p3[k].coeff=p1[i].coeff;

p3[k].expo=p1[i].expo;

i++;

k++;

}
/* for rest over terms of polynomial 2 */

while(j<t2)

p3[k].coeff=p2[j].coeff;

p3[k].expo=p2[j].expo;

j++;

k++;

return(k); /* k is number of terms in resultant polynomial*/

void displayPoly(struct poly p[10],int term)

int k;

for(k=0;k<term-1;k++)

printf("%d(x^%d)+",p[k].coeff,p[k].expo);

printf("%d(x^%d)",p[term-1].coeff,p[term-1].expo);

9. Write a program to push 5,9,34,17,32 into stack and pop 3 times from the stack, also display the
popped numbers.

#include<stdio.h>

#include<process.h>

#include<stdlib.h>

#define MAX 5 //Maximum number of elements that can be stored

int top=-1,stack[MAX];
void push();

void pop();

void display();

void main()

int ch;

while(1) //infinite loop, will end when choice will be 4

printf("\n** Stack Menu **");

printf("\n\n1.Push\n2.Pop\n3.Display\n4.Exit");

printf("\n\nEnter your choice(1-4):");

scanf("%d",&ch);

switch(ch)

case 1: push();

break;

case 2: pop();

break;

case 3: display();

break;

case 4: exit(0);

default: printf("\nWrong Choice!!");

void push()

int val;

if(top==MAX-1)
{

printf("\nStack is full!!");

else

printf("\nEnter element to push:");

scanf("%d",&val);

top=top+1;

stack[top]=val;

void pop()

if(top==-1)

printf("\nStack is empty!!");

else

printf("\nDeleted element is %d",stack[top]);

top=top-1;

void display()

int i;

if(top==-1)

printf("\nStack is empty!!");
}

else

printf("\nStack is...\n");

for(i=top;i>=0;--i)

printf("%d\n",stack[i]);

10 . Write a recursive program to find GCD of 4,6,8.

#include <stdio.h>

int hcf(int n1, int n2);

int main() {

int n1, n2;

printf("Enter two positive integers: ");

scanf("%d %d", &n1, &n2);

printf("G.C.D of %d and %d is %d.", n1, n2, hcf(n1, n2));

return 0;

int hcf(int n1, int n2) {

if (n2 != 0)

return hcf(n2, n1 % n2);

else

return n1;

12. Write a program to convert an infix expression x^y/(5*z)+2 to its postfix expression

#include<stdio.h>

#include<stdlib.h> /* for exit() */

#include<ctype.h> /* for isdigit(char ) */


#include<string.h>

#define SIZE 100

/* declared here as global variable because stack[]

* is used by more than one fucntions */

char stack[SIZE];

int top = -1;

/* define push operation */

void push(char item)

if(top >= SIZE-1)

printf("\nStack Overflow.");

else

top = top+1;

stack[top] = item;

/* define pop operation */

char pop()

char item ;

if(top <0)
{

printf("stack under flow: invalid infix expression");

getchar();

/* underflow may occur for invalid expression */

/* where ( and ) are not matched */

exit(1);

else

item = stack[top];

top = top-1;

return(item);

/* define function that is used to determine whether any symbol is operator or not

(that is symbol is operand)

* this fucntion returns 1 if symbol is opreator else return 0 */

int is_operator(char symbol)

if(symbol == '^' || symbol == '*' || symbol == '/' || symbol == '+' || symbol =='-')

return 1;

else

return 0;

}
/* define fucntion that is used to assign precendence to operator.

* Here ^ denotes exponent operator.

* In this fucntion we assume that higher integer value

* means higher precendence */

int precedence(char symbol)

if(symbol == '^')/* exponent operator, highest precedence*/

return(3);

else if(symbol == '*' || symbol == '/')

return(2);

else if(symbol == '+' || symbol == '-') /* lowest precedence */

return(1);

else

return(0);

void InfixToPostfix(char infix_exp[], char postfix_exp[])

int i, j;

char item;

char x;
push('('); /* push '(' onto stack */

strcat(infix_exp,")"); /* add ')' to infix expression */

i=0;

j=0;

item=infix_exp[i]; /* initialize before loop*/

while(item != '\0') /* run loop till end of infix expression */

if(item == '(')

push(item);

else if( isdigit(item) || isalpha(item))

postfix_exp[j] = item; /* add operand symbol to postfix expr */

j++;

else if(is_operator(item) == 1) /* means symbol is operator */

x=pop();

while(is_operator(x) == 1 && precedence(x)>= precedence(item))

postfix_exp[j] = x; /* so pop all higher precendence


operator and */

j++;

x = pop(); /* add them to postfix expresion */

push(x);

/* because just above while loop will terminate we have

oppped one extra item


for which condition fails and loop terminates, so that one*/

push(item); /* push current oprerator symbol onto stack */

else if(item == ')') /* if current symbol is ')' then */

x = pop(); /* pop and keep popping until */

while(x != '(') /* '(' encounterd */

postfix_exp[j] = x;

j++;

x = pop();

else

{ /* if current symbol is neither operand not '(' nor ')' and nor

operator */

printf("\nInvalid infix Expression.\n"); /* the it is illegeal symbol */

getchar();

exit(1);

i++;

item = infix_exp[i]; /* go to next symbol of infix expression */

} /* while loop ends here */

if(top>0)

printf("\nInvalid infix Expression.\n"); /* the it is illegeal symbol */

getchar();

exit(1);
}

if(top>0)

printf("\nInvalid infix Expression.\n"); /* the it is illegeal symbol */

getchar();

exit(1);

postfix_exp[j] = '\0'; /* add sentinel else puts() fucntion */

/* will print entire postfix[] array upto SIZE */

/* main function begins */

int main()

char infix[SIZE], postfix[SIZE]; /* declare infix string and postfix string */

/* why we asked the user to enter infix expression

* in parentheses ( )

* What changes are required in porgram to

* get rid of this restriction since it is not

* in algorithm

* */

printf("ASSUMPTION: The infix expression contains single letter variables and single digit
constants only.\n");

printf("\nEnter Infix expression : ");

gets(infix);

InfixToPostfix(infix,postfix); /* call to convert */


printf("Postfix Expression: ");

puts(postfix); /* print postfix expression */

return 0;

13 . Write a program to evaluate a postfix expression 5 3+8 2 - *.

#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;

15 . Program for binary tree traversals in inorder, preorder, and postorder

#include <stdio.h>

#include <stdlib.h>

struct node {

int item;

struct node* left;

struct node* right;

};

// Inorder traversal

void inorderTraversal(struct node* root) {

if (root == NULL) return;

inorderTraversal(root->left);

printf("%d ->", root->item);

inorderTraversal(root->right);

// preorderTraversal traversal

void preorderTraversal(struct node* root) {


if (root == NULL) return;

printf("%d ->", root->item);

preorderTraversal(root->left);

preorderTraversal(root->right);

// postorderTraversal traversal

void postorderTraversal(struct node* root) {

if (root == NULL) return;

postorderTraversal(root->left);

postorderTraversal(root->right);

printf("%d ->", root->item);

// Create a new Node

struct node* createNode(value) {

struct node* newNode = malloc(sizeof(struct node));

newNode->item = value;

newNode->left = NULL;

newNode->right = NULL;

return newNode;

// Insert on the left of the node

struct node* insertLeft(struct node* root, int value) {

root->left = createNode(value);

return root->left;

// Insert on the right of the node


struct node* insertRight(struct node* root, int value) {

root->right = createNode(value);

return root->right;

int main() {

struct node* root = createNode(1);

insertLeft(root, 12);

insertRight(root, 9);

insertLeft(root->left, 5);

insertRight(root->left, 6);

printf("Inorder traversal \n");

inorderTraversal(root);

printf("\nPreorder traversal \n");

preorderTraversal(root);

printf("\nPostorder traversal \n");

postorderTraversal(root);

16 . Write a program to Sort the following elements using heap sort {9.16,32,8,4,1,5,8,0}

// Heap Sort in C

#include <stdio.h>

// Function to swap the the position of two elements

void swap(int *a, int *b) {

int temp = *a;


*a = *b;

*b = temp;

void heapify(int arr[], int n, int i) {

// Find largest among root, left child and right child

int largest = i;

int left = 2 * i + 1;

int right = 2 * i + 2;

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

largest = left;

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

largest = right;

// Swap and continue heapifying if root is not largest

if (largest != i) {

swap(&arr[i], &arr[largest]);

heapify(arr, n, largest);

// Main function to do heap sort

void heapSort(int arr[], int n) {

// Build max heap

for (int i = n / 2 - 1; i >= 0; i--)

heapify(arr, n, i);

// Heap sort

for (int i = n - 1; i >= 0; i--) {


swap(&arr[0], &arr[i]);

// Heapify root element to get highest element at root again

heapify(arr, i, 0);

// Print an array

void printArray(int arr[], int n) {

for (int i = 0; i < n; ++i)

printf("%d ", arr[i]);

printf("\n");

// Driver code

int main() {

int arr[] = {1, 12, 9, 5, 6, 10};

int n = sizeof(arr) / sizeof(arr[0]);

heapSort(arr, n);

printf("Sorted array is \n");

printArray(arr, n);

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy