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

Data Structures Lab

Uploaded by

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

Data Structures Lab

Uploaded by

rajwaruk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

NAME: RAJWA

CLASS: BCA 2nd SEMESTER


SUBJECT: DATA STRUCTURES LAB
PART A:
(1) WRITE AN INTERACTIVE PROGRAM TO SEARCH AN ELEMENT IN THE
GIVEN LINEAR ARRAY USING LINEAR AND BINARY SEARCHING TECHNIQUE.

/* Program to implement linear search and Binary search */

#include<stdio.h>
#include<stdlib.h>
main()
{
/* Declare variables - array_of_number,search_key,i,j,low,high*/
Int array[100],search_key,i,j,n,low,high,location,choice;
void linear_search(int search_key,int array[100],int n);
void binary_search(int search_key,int array[100],int n);
clrscr();

/* read the elements of array */


printf("ENTER THE SIZE OF THE ARRAY:");
scanf("%d",&n);
printf("ENTER THE ELEMENTS OF THE ARRAY:\n");
for(i=1;i<=n;i++)
{
scanf("%d",&array[i]);
}

/* Get the Search Key element for Linear Search */


printf("ENTER THE SEARCH KEY:");
scanf("%d",&search_key);

/* Choice of Search Algorithm */


printf("___________________\n");
printf("1.LINEAR SEARCH\n");
printf("2.BINARY SEARCH\n");
printf("___________________\n");
printf("ENTER YOUR CHOICE:");
scanf("%d",&choice);
switch(choice)
{
case 1:
linear_search(search_key,array,n);
break;
case 2:
binary_search(search_key,array,n);
break;
default:
exit(0);
}
getch();
return 0;
}

/* LINEAR SEARCH */
void linear_search(int search_key,int array[100],int n)
{

/*Declare Variable */
int i,location;
for(i=1;i<=n;i++)
{
if(search_key == array[i])
{
location = i;
printf("______________________________________\n");
printf("The location of Search Key = %d is %d\n",search_key,location);
printf("______________________________________\n");
}
}
}

/* Binary Search to find Search Key */


void binary_search(int search_key,int array[100],int n)
{
int mid,i,low,high;
low = 1;
high = n;
mid = (low + high)/2;
i=1;
while(search_key != array[mid])
{
if(search_key <= array[mid])
{
low = 1;
high = mid+1;
mid = (low+high)/2;
}
else
{
low = mid+1;
high = n;
mid = (low+high)/2;
}
}
printf("__________________________________\n");
printf("location=%d\t",mid);
printf("Search_Key=%d Found!\n",search_key);
printf("__________________________________\n");
}
OUTPUT:
ENTER THE SIZE OF THE ARRAY:6
ENTER THE ELEMENTS OF THE ARRAY:
45
6
86
23
64
77
ENTER THE SEARCH KEY:86
____________________
1. LINEAR SEARCH
2. BINARY SEARCH
____________________
ENTER YOUR CHOICE:2
________________________________________
_____
Location =3 Search_Key = 86 Found!
(2) WRITE A PROGRAM TO ARRANGE NUMBERS IN ASCENDING ORDER USING INSERTION
SORT.

/* C Program to sort an array in ascending order using Insertion Sort */


#include<stdio.h>
int main()
{
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 - 1; 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 - 1; i++)
{
printf("%d\n", arr[i]);
}
return 0;
}
OUTPUT:
/* Average case */
Enter number of elements
6
Enter 6 integers
461253
Sorted list in ascending order:
1
2
3
4
5
6
(3) WRITE A PROGRAM TO ARRANGE NUMBERS IN ASCENDING ORDER USING
MERGE SORT

/* C program for Merge Sort */


#include<stdio.h>
#include<stdlib.h>
// Merges two subarrays of arr[].
//First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];

/* Merge the temp arrays back into arr[l..r]*/


i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}

/* Copy the remaining elements of L[], if there are any */


while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

/* Copy the remaining elements of R[], if there are any */


while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

/* l is for left index and r is right index of the sub-array of arr to be sorted */
void mergeSort(int arr[], int l, int r)
{
if (l < r) {
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l + (r - l) / 2;

// Sort first and second halves


mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}

/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(int A[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}

/* Driver code *
/ int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);

printf("Given array is \n");


printArray(arr, arr_size);

mergeSort(arr, 0, arr_size - 1);

printf("\nSorted array is \n");


printArray(arr, arr_size);
return 0;
}
OUTPUT:
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
(4) WRITE A PROGRAM TO ARRANGE NUMBERS IN ASCENDING ORDER USING
SELECTION SORT

#include<stdio.h>
int main()
{
int arr[10]={6,12,0,18,11,99,55,45,34,2};
int n=10;
int i, j, position, swap;
for (i = 0; i < (n - 1); i++) {
position = i;
for (j = i + 1; j < n; j++) {
if (arr[position] > arr[j])
position = j;
}
if (position != i) {
swap = arr[i];
arr[i] = arr[position];
arr[position] = swap;
}
}
for (i = 0; i < n; i++)
printf("%d\t", arr[i]);
return 0;
}
OUTPUT:
0 2 6 11 12 18 34 45 55 99
(5) WRITE A PROGRAM TO ARRANGE NUMBERS IN ASCENDING ORDER USING
QUICK SORT
#include<stdio.h>
void quicksort (int [], int, int);
int main()
{
int list[50];
int size, i;
printf("Enter the number of elements: ");
scanf("%d", &size);
printf("Enter the elements to be sorted:\n");
for (i = 0; i < size; i++)
{
scanf("%d", &list[i]);
}
quicksort(list, 0, size - 1);
printf("After applying quick sort\n");
for (i = 0; i < size; i++)
{
printf("%d ", list[i]);
}
printf("\n");
return 0;
}
void quicksort(int list[], int low, int high)
{
int pivot, i, j, temp;
if (low < high)
{
pivot = low;
i = low;
j = high;
while (i < j)
{
while (list[i] <= list[pivot] && i <= high)
{
i++;
}
while (list[j] > list[pivot] && j >= low)
{
j--;
}
if (i < j)
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
temp = list[j];
list[j] = list[pivot];
list[pivot] = temp;
quicksort(list, low, j - 1);
quicksort(list, j + 1, high);
}
}

OUTPUT:
Enter the number of elements: 6

Enter the elements to be sorted:

67

45

24

98

12

38

After applying quick sort

12 24 38 45 67 98
(6) WRITE AN INTERACTIVE PROGRAM TO INSERT AN ELEMENT AT THE GIVEN POSITION AND
DELETE AN ELEMENT AT THE SPECIFIED POSITION IN THE GIVEN ARRAY

#include<stdio.h>
#include<stdlib.h>
int main()
{
int a[100];
int element,i,loc,size;
printf("Enter the size of an array\n");
scanf("%d",&size);
printf("Enter %d array elements\n",size);
for(i=0;i<size;i++)
{
scanf("%d",&a[i]);
}
printf("List before Insertion: ");
for(i=0;i<size;i++)
{
printf("%d ",a[i]);
}
printf("\nEnter an element to insert\n");
scanf("%d",&element);
printf("Enter a position to insert an element %d\n",element);
scanf("%d",&loc);
loc--;
for(i=size-1;i>=loc;i--)
{
a[i+1]=a[i];
}
a[loc]=element;
printf("\nList after Insertion: ");
for(i=0;i<size+1;i++)
{
printf("%d ",a[i]);
}
return 0;
}
OUTPUT:

Enter the size of an array

Enter 5 array elements

6 7 41 23 1

List before Insertion: 6 7 41 23 1

Enter an element to insert

10

Enter an position to insert an element 10

List after Insertion: 6 7 10 41 23 1

#include<stdio.h>
#include<stdlib.h>
int main()
{
int a[100],size,n,i,j;
printf("Enter the size of an array\n");
scanf("%d",&size);
printf("Enter elements\n");
for(i=0;i<size;i++)
{
scanf("%d",&a[i]);
}
printf("List before deletion\n");
for(i=0;i<size;i++)
{
printf("%d ",a[i]);
}
printf("\nEnter an element to delete\n");
scanf("%d",&n);
for(i=0;i<size;i++)
{
if(a[i]==n)
{
for(j=i;j<(size-1);j++)
{
a[j]=a[j+1];
}
break;
}
}
printf("List after deletion\n");
for(i=0;i<(size-1);i++)
{
printf("%d ",a[i]);
}
return 0;
}
OUTPUT:

Enter the size of an array

Enter elements

12345

List before deletion

12345

Enter an element to delete

List after deletion

1245
(7) WRITE AN INTERACTIVE PROGRAM TO IMPLEMENT THE
FOLLOWING OPERATIONS ON STACK
#include<stdio.h>
#include<stdlib.h>
#include<limits.h> // For INT_MIN
#define SIZE 100
// Create a stack with capacity of 100 elements int stack[SIZE];
//Initially stack is empty
int top = -1;
/* Function declaration to perform push and pop on stack */
void push(int element);
int pop();

int main()
{
int choice, data;

while(1)
{
/* Menu */
printf("------------------------------------\n");
printf(" STACK IMPLEMENTATION PROGRAM \n");
printf("------------------------------------\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Size\n");
printf("4. Exit\n");
printf("------------------------------------\n");
printf("Enter your choice: ");

scanf("%d", &choice);

switch(choice)
{
case 1:
printf("Enter data to push into stack: ");
scanf("%d", &data);
// Push element to stack
push(data);
break;
case 2: data = pop();

// If stack is not empty


if (data != INT_MIN)
printf("Data => %d\n", data);
break;
case 3:
printf("Stack size: %d\n", top + 1);
break;
case 4:
printf("Exiting from app.\n");
exit(0);
break;
default:
printf("Invalid choice, please try again.\n");
}

printf("\n\n");
}

return 0;
}

/**
* Functiont to push a new element in stack.
*/
void push(int element)
{
// Check stack overflow
if (top >= SIZE)
{
printf("Stack Overflow, can't add more element element to stack.\n");
return;
}

// Increase element count in stack


top++;

// Push element in stack


stack[top] = element;
printf("Data pushed to stack.\n");
}

/**
* Function to pop element from top of stack.
*/
int pop()
{
// Check stack underflow
if (top < 0)
{
printf("Stack is empty.\n");
// Throw empty stack error/exception
// Since C does not have concept of exception
// Hence return minimum integer value as error value
// Later in code check if return value is INT_MIN, then
// stack is empty
return INT_MIN;
}
// Return stack top and decrease element count in stack return stack[top--];
}

OUTPUT:
------------------------------------
STACK IMPLEMENTATION PROGRAM
------------------------------------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 2
Stack is empty.

------------------------------------
STACK IMPLEMENTATION PROGRAM
------------------------------------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice:
1
Enter data to push into stack: 10
Data pushed to stack.

------------------------------------
STACK IMPLEMENTATION PROGRAM
------------------------------------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 1
Enter data to push into stack: 20
Data pushed to stack.

------------------------------------
STACK IMPLEMENTATION PROGRAM
------------------------------------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 1
Enter data to push into stack: 30
Data pushed to stack.

------------------------------------
STACK IMPLEMENTATION PROGRAM
------------------------------------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 3
Stack size: 3

------------------------------------
STACK IMPLEMENTATION PROGRAM
------------------------------------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 2
Data => 30

------------------------------------
STACK IMPLEMENTATION PROGRAM
------------------------------------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 2
Data => 20

------------------------------------
STACK IMPLEMENTATION PROGRAM
------------------------------------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 2
Data => 10

------------------------------------
STACK IMPLEMENTATION PROGRAM
------------------------------------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 2
Stack is empty.

------------------------------------
STACK IMPLEMENTATION PROGRAM
------------------------------------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 4
Exiting from app.
(8) PROGRAM TO IMPLEMENT TOWER OF HANOI PROBLEM.

#include<stdio.h>

void towers(int, char, char, char);

int main()
{
int num;
printf("Enter the number of disks : ");
scanf("%d", &num);
printf("The sequence of moves involved in the Tower of Hanoi are :\n");
towers(num, 'A', 'C', 'B');
return 0;
}
void towers(int num, char frompeg, char topeg, char auxpeg)
{
if (num == 1)
{
printf("\n Move disk 1 from peg %c to peg %c", frompeg, topeg);
return;
}
towers(num - 1, frompeg, auxpeg, topeg);
printf("\n Move disk %d from peg %c to peg %c", num, frompeg, topeg);
towers(num - 1, auxpeg, topeg, frompeg);
}
OUTPUT:

Enter the number of disks : 3

The sequence of moves involved in the Tower of Hanoi are :

Move disk 1 from peg A to peg C

Move disk 2 from peg A to peg B

Move disk 1 from peg C to peg B

Move disk 3 from peg A to peg C

Move disk 1 from peg B to peg A

Move disk 2 from peg B to peg C

Move disk 1 from peg A to peg C


PART B:

(1) WRITE PROGRAM TO EVALUATE A POSTFIX EXPRESSION.

#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;
}
OUTPUT:

Enter the expression :: 245+*

The result of expression 245+* = 18


(2) WRITE A PROGRAM TO CONVERT AN EXPRESSION FROM INFIX
TO POSTFIX
#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;
}
Output Test Case 1:

Enter the expression : a+b*c

abc*+

Output Test Case 2:

Enter the expression : (a+b)*c+(d-a)

ab+c*da-+

Output Test Case 3:

Enter the expression : ((4+8)(6-5))/((3-2)(2+2))

48+65-32-22+/
(3) WRITE AN INTERACTIVE PROGRAM TO PERFORM INSERTION
AND DELETION OPERATIONS IN LINEAR QUEUE

#include<stdio.h>
#define MAX 5
//Declaration of Queue typedef struct queue
{
int front ;
int rear ;
int ele[MAX] ;
}Queue;

//Intialze Queue void init(Queue *q)


{
q->rear = -1;
q->front = 0;
}

//To check Queue is full or not int isFull(Queue *q)


{
int full=0;
if( q->rear == MAX -1) full = 1;
return full;
}

//To check Queue is empty or not int isEmpty(Queue *q)


{
int empty=0;
if( q->front == q->rear+1 )
empty = 1;
return empty;
}

//Insert item into queue void insertQueue(Queue *q,int item)


{
if( isFull(q) )
{
printf("\nQueue Overflow");
return;
}
q->ele[++(q->rear)] = item;
printf("\nInserted item : %d",item);
}

//Delete item from queue int deleteQueue(Queue *q, int * item)


{
if( isEmpty(q) )
{
printf("\nQueue Underflow");
return -1;
}
*item = q->ele[(q->front)++];
return 0;
}
int main()
{
int item = 0;
Queue q;
init(&q);

insertQueue(&q,10);
insertQueue(&q,20);
insertQueue(&q,30);
insertQueue(&q,40);
insertQueue(&q,50);
insertQueue(&q,60);

if( deleteQueue( &q, &item ) == 0 )


printf("\nDeleted item : %d",item);
if( deleteQueue( &q, &item ) == 0 )
printf("\nDeleted item : %d",item);
if( deleteQueue( &q, &item ) == 0 )
printf("\nDeleted item : %d",item);
if( deleteQueue( &q, &item ) == 0 )
printf("\nDeleted item : %d",item);
if( deleteQueue( &q, &item ) == 0 )
printf("\nDeleted item : %d",item);
if( deleteQueue( &q, &item ) == 0 )
printf("\nDeleted item : %d",item);
printf("\n");
return 0;
}

OUTPUT:

Output

Inserted item : 10

Inserted item : 20

Inserted item : 30

Inserted item : 40

Inserted item : 50

Queue Overflow

Deleted item : 10

Deleted item : 20

Deleted item : 30

Deleted item : 40

Deleted item : 50

Queue Underflow
(4) Write an interactive program to perform insertion and deletion
operations in Circular Queue
#include<stdio.h>
using namespace std;
int cqueue[5];
int front = -1, rear = -1, n=5;
void insertCQ(int val) {
if ((front == 0 && rear == n-1) || (front == rear+1)) {
cout<<"Queue Overflow \n";
return;
}
if (front == -1) {
front = 0;
rear = 0;
}
else {
if (rear == n - 1)
rear = 0;
else
rear = rear + 1;
}
cqueue[rear] = val ;
}
void deleteCQ() {
if (front == -1) {
cout<<"Queue Underflow\n";
return ;
}
cout<<"Element deleted from queue is : "<<cqueue[front]<<endl;
if (front == rear) {
front = -1;
rear = -1;
}
else {
if (front == n - 1)
front = 0;
else
front = front + 1;
}
}
void displayCQ() {
int f = front, r = rear;
if (front == -1) {
cout<<"Queue is empty"<<endl;
return;
}
cout<< "Queue elements are :\n";
if (f <= r) {
while (f <= r){
cout<<cqueue[f]<<" ";
f++;
}
} else {
while (f <= n - 1) {
cout<<cqueue[f]<<" ";
f++;
}
f = 0;
while (f <= r) {
cout<<cqueue[f]<<" ";
f++;
}
}
cout<<endl;
}
int main() {
int ch, val;
cout<<"1)Insert\n";
cout<<"2)Delete\n";
cout<<"3)Display\n";
cout<<"4)Exit\n";
do {
cout<<"Enter choice : "<<endl;
cin>>ch;
switch(ch) {
case 1:
cout<<"Input for insertion: "<<endl;
cin>>val;
insertCQ(val);
break;
case 2:
deleteCQ();
break;
case 3:
displayCQ();
break;
case 4:
cout<<"Exit\n";
break;
default: cout<<"Incorrect!\n";
}
} while(ch != 4);
return 0;
}
Output

1)Insert

2)Delete

3)Display

4)Exit

Enter choice :

Input for insertion:

10

Enter choice :

Input for insertion:

20

Enter choice :

Input for insertion:

30

Enter choice :

Input for insertion:

40

Enter choice :

Input for insertion:

50

Enter choice :

Queue elements are :

10 20 30 40 50

Enter choice :

Element deleted from queue is : 10

Enter choice :

2
(5) WRITE A PROGRAM TO DELETE AN ITEM FROM THE LINKED LIST.
// A complete working C program
// to demonstrate deletion in
// singly linked list
#include<stdio.h>
#include<stdlib>
// A linked list node
struct Node {
int data;
struct Node* next;
};

/* Given a reference (pointer to pointer) to the head of a list and an


int, inserts a new node on the front of the list. */
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node
=(struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}

/* Given a reference (pointer to pointer) to the head of a list and a


key, deletes the first occurrence of key in linked list */
void deleteNode(struct Node** head_ref, int key)
{
// Store head node struct Node *temp = *head_ref, *prev;

// If head node itself holds the key to be deleted


if (temp != NULL && temp->data == key) {
*head_ref = temp->next; // Changed head
free(temp); // free old head
return;
}
// Search for the key to be deleted, keep track of the
// previous node as we need to change 'prev->next'
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}

// If key was not present in linked list


if (temp == NULL)
return;

// Unlink the node from linked list


prev->next = temp->next;
free(temp); // Free memory
}

// This function prints contents of linked list starting


// from the given node
void printList(struct Node* node)
{
while (node != NULL) {
printf(" %d ", node->data);
node = node->next;
}
}

// Driver code
int main()
{
/* Start with the empty list */ struct Node*
head = NULL;
push(&head, 7);
push(&head, 1);
push(&head, 3);
push(&head, 2);

puts("Created Linked List: ");


printList(head);
deleteNode(&head, 1);
puts("\nLinked List after Deletion of 1: ");
printList(head);
return 0;
}
OUTPUT:
Created Linked List:

2317

Linked List after Deletion of 1:

237
(6) WRITE AN INTERACTIVE PROGRAM TO IMPLEMENT STACK
OPERATIONS USING SINGLY LINKED LIST.

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

// A Linked List Node


struct Node
{
int data; // integer data
struct Node* next; // pointer to the next node
};

int nodesCount;

// Utility function to add an element `x` to the stack


void push(struct Node **top, int x) // insert at the beginning
{
// allocate a new node in a heap
struct Node* node = NULL;
node = (struct Node*)malloc(sizeof(struct Node));

// check if stack (heap) is full. Then inserting an element would


// lead to stack overflow
if (!node)
{
printf("Heap Overflow\n");
exit(-1);
}
printf("Inserting %d\n", x);
// set data in the allocated node node->data = x;
// set the .next pointer of the new node to point to the current
// top node of the list node->next = *top;
// update top pointer *top = node;
// increase stack's size by 1
nodesCount += 1;
}

// Utility function to check if the stack is empty or not int


isEmpty(struct Node* top) {
return top == NULL;
}

// Utility function to return the top element of the stack


int peek(struct Node *top)
{
//check for an empty stack
if (!isEmpty(top)) {
return top->data;
}
else {
printf("The stack is empty\n");
exit(EXIT_FAILURE);
}
}

// Utility function to pop a top element from the stack


int pop(struct Node** top)
// remove at the beginning { struct Node *node;
// check for stack underflow
if (*top == NULL)
{
printf("Stack Underflow\n");
exit(EXIT_FAILURE);
}
// take note of the top node's data
int x = peek(*top);
printf("Removing %d\n", x);
node = *top;
// update the top pointer to point to the next node *top = (*top)-
>next;
// decrease stack's size by 1 nodesCount -= 1;
// free allocated memory free(node); return x; }
// Utility function to return the nodesCount of the stack int size()
{
return nodesCount;
}
int main(void)
{
struct Node* top = NULL;
push(&top, 1);
push(&top, 2);
push(&top, 3);
printf("The top element is %d\n", peek(top));
pop(&top);
pop(&top);
pop(&top);
if (isEmpty(top))
{
printf("The stack is empty\n");
}
else
{
printf("The stack is not empty\n");
}
return 0;
}
Output:

Inserting 1

Inserting 2

Inserting 3

The top element is 3

Removing 3

Removing 2

Removing 1

The stack is empty


(7) WRITE AN INTERACTIVE PROGRAM TO PERFORM INSERTION
OPERATION IN LINKED LIST- AT THE BEGINNING, AT THE END AND
IN-BETWEEN.

#include<stdio.h>
#include<stdlib>
void beginsert(int);
struct node
{
int data;
struct node *next;
};
struct node *head;
void main ()
{
int choice,item;
do
{
printf("\nEnter the item which you want to insert?\n");
scanf("%d",&item);
beginsert(item);
printf("\nPress 0 to insert more ?\n");
scanf("%d",&choice);
}while(choice == 0);
}
void beginsert(int item)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node*));
if(ptr == NULL)
{
printf("\nOVERFLOW\n");
}
else
{
ptr->data = item;
ptr->next = head;
head = ptr;
printf("\nNode inserted\n");
}
}
Output

Enter the item which you want to insert?

12

Node inserted

Press 0 to insert more ?

Enter the item which you want to insert?

23

Node inserted

Press 0 to insert more ?

#include<stdio.h>
#include<stdlib>
void lastinsert(int);
struct node
{
int data; struct node *next;
};
struct node *head;
void main ()
{
int choice,item;
do
{
printf("\nEnter the item which you want to insert?\n");
scanf("%d",&item);
lastinsert(item);
printf("\nPress 0 to insert more ?\n");
scanf("%d",&choice);
}while(choice == 0);
}
void lastinsert(int item)
{
struct node *ptr = (struct node*)malloc(sizeof(struct node));
struct node *temp;
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
ptr->data = item;
if(head == NULL)
{
ptr -> next = NULL;
head = ptr;
printf("\nNode inserted");
}
else
{
temp = head;
while (temp -> next != NULL)
{
temp = temp -> next;
}
temp->next = ptr;
ptr->next = NULL;
printf("\nNode inserted");
}
}
}
Output

Enter the item which you want to insert?

12

Node inserted

Press 0 to insert more ?

Enter the item which you want to insert?

23

Node inserted

Press 0 to insert more ?

2
(8) PROGRAM TO CREATE A BINARY TREE AND ALSO PRINT THE
PREORDER VALUES, INORDER VALUES, POSTORDER VALUES.

// C program for different tree traversals #include #include<stdio.h>


#include<stdlib>

/* A binary tree node has data, pointer to left child and a pointer to right child
*/

struct node {
int data;
struct node* left;
struct node* right;
};

/* Helper function that allocates a new node with the given data and NULL left
and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;

return (node);
}

/* Given a binary tree, print its nodes according to the "bottom-up" postorder
traversal. */
void printPostorder(struct node* node)
{
if (node == NULL)
return;
// first recur on left subtree
printPostorder(node->left);

// then recur on right subtree


printPostorder(node->right);

// now deal with the node


printf("%d ", node->data);
}

/* Given a binary tree, print its nodes in inorder*/


void printInorder(struct node* node)
{
if (node == NULL)
return;
/* first recur on left child */
printInorder(node->left);
/* then print the data of node */
printf("%d ", node->data);
/* now recur on right child */
printInorder(node->right);
}

/* Given a binary tree, print its nodes in preorder*/ void printPreorder(struct


node* node)
{
if (node == NULL)
return;

/* first print data of node */


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

/* then recur on left subtree */


printPreorder(node->left);

/* now recur on right subtree */


printPreorder(node->right);
}

/* Driver program to test above functions*/


int main()
{
struct node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("\nPreorder traversal of binary tree is \n");
printPreorder(root);
printf("\nInorder traversal of binary tree is \n");
printInorder(root);

printf("\nPostorder traversal of binary tree is \n");


printPostorder(root);
getchar();
return 0;
}

Output:

Preorder traversal of binary tree is

12453

Inorder traversal of binary tree is

42513

Postorder traversal of binary tree is

45231
(9) WRITE A PROGRAM TO ADD TWO POLYNOMIALS OF ONE
VARIABLE AND ‗N‘ DEGREE AND REPRESENT THEM AS LINKED LIST.

#include<stdio.h>
#include<math.h>

/* This structure is used to store a polynomial term. An array of such terms


represents a polynomial.
The "coeff" element stores the coefficient of a term in the polynomial,while
the "exp" element stores the exponent.
*/ struct poly
{
float coeff;
int exp;
};

//declaration of polynomials
struct poly a[50],b[50],c[50],d[50];
int main()
{
int i;
int deg1,deg2; //stores degrees of the polynomial
int k=0,l=0,m=0;

printf("Enter the highest degree of poly1:");


scanf("%d",°1);
//taking polynomial terms from the user
for(i=0;i<=deg1;i++)
{
//entering values in coefficient of the polynomial terms printf("\nEnter the
coeff of x^%d :",i);
scanf("%f",&a[i].coeff);
//entering values in exponent of the polynomial terms
a[k++].exp = i;
}
//taking second polynomial from the user
printf("\nEnter the highest degree of poly2:");
scanf("%d",°2);
for(i=0;i<=deg2;i++)
{
printf("\nEnter the coeff of x^%d :",i);
scanf("%f",&b[i].coeff);
b[l++].exp = i;
}
//printing first polynomial
printf("\nExpression 1 = %.1f",a[0].coeff);
for(i=1;i<=deg1;i++)
{
printf("+ %.1fx^%d",a[i].coeff,a[i].exp);
}

//printing second polynomial


printf("\nExpression 2 = %.1f",b[0].coeff);
for(i=1;i<=deg2;i++)
{
printf("+ %.1fx^%d",b[i].coeff,b[i].exp);
}

//Adding the polynomials


if(deg1>deg2)
{
for(i=0;i<=deg2;i++)
{
c[m].coeff = a[i].coeff + b[i].coeff;
c[m].exp = a[i].exp;
m++;
}
for(i=deg2+1;i<=deg1;i++)
{
c[m].coeff = a[i].coeff;
c[m].exp = a[i].exp; m++;
}
}
else
{
for(i=0;i<=deg1;i++)
{
c[m].coeff = a[i].coeff + b[i].coeff;
c[m].exp = a[i].exp;
m++;
}

for(i=deg1+1;i<=deg2;i++)
{
c[m].coeff = b[i].coeff;
c[m].exp = b[i].exp;
m++;
}
//printing the sum of the two polynomials
printf("\nExpression after additon = %.1f",c[0].coeff);
for(i=1;i<m;i++)
{
printf("+ %.1fx^%d",c[i].coeff,c[i].exp);
}
return 0;
}
Output

Enter the highest degree of poly1:5

Enter the coeff of x^0 :1

Enter the coeff of x^1 :2

Enter the coeff of x^2 :3

Enter the coeff of x^3 :4

Enter the coeff of x^4 :5

Enter the coeff of x^5 :6

Enter the highest degree of poly2:4

Enter the coeff of x^0 :4

Enter the coeff of x^1 :3

Enter the coeff of x^2 :2

Enter the coeff of x^3 :1

Enter the coeff of x^4 :0

Expression 1 = 1.0+ 2.0x^1+ 3.0x^2+ 4.0x^3+ 5.0x^4+ 6.0x^5

Expression 2 = 4.0+ 3.0x^1+ 2.0x^2+ 1.0x^3+ 0.0x^4

Expression after additon = 5.0+ 5.0x^1+ 5.0x^2+ 5.0x^3+ 5.0x^4+ 6.0x^5

You might also like