0% found this document useful (0 votes)
57 views56 pages

2nd Sem Ds Lab

notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views56 pages

2nd Sem Ds Lab

notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 56

1. Write a Program to create, Initialize and access a pointer variable.

/* Simple Program for Length of String Using Pointer in C*/

/* Print Pointer Address Program,C Pointer Examples */

#include<stdio.h>

int main() {

char str[20], *pt;

int i = 0;

printf("Pointer Example Program : Find or Calculate Length of String \n");

printf("Enter Any string [below 20 chars] : ");

gets(str);

pt = str;

while (*pt != '\0') {

i++;

pt++;

printf("Length of String : %d", i);

return 0;

Output:

Pointer Example Program : Find or Calculate Length of String

Enter Any string [below 20 chars] : FIND-STRING-LENGTH

Length of String : 18
2. Write a Program to Calculate the length of the string using a pointer.

#include <stdio.h>

int main() {

char str[100];

char *ptr = str;

printf("Enter string: ");

gets(str);

// Find string length using pointers

int length = 0;

while (*ptr != '\0') {

length++;

ptr++;

// Display string length

printf("Length of the given string '%s': %d\n", str, length);

return 0;

Output:

Enter string: procoding

Length of the given string 'procoding': 9

3. Write a Program to swap numbers using pointer.

#include<stdio.h>

void swap(int*, int*);


int main()

int a, b;

printf("Enter values for a and b\n");

scanf("%d%d", &a, &b);

printf("\n\nBefore swapping: a = %d and b = %d\n", a, b);

swap(&a, &b);

printf("\nAfter swapping: a = %d and b = %d\n", a, b);

return 0;

void swap(int *x, int *y)

int temp;

temp = *x;

*x = *y;

*y = temp;

}
Output:

Enter values for a and b

30

20

Before swapping: a = 30 and b = 20

After swapping: a = 20 and b = 30

4. Write a program in C to print all permutations of a given string using pointers.

#include<stdio.h>

#include<string.h>

//Declaring generatePermutation()

void generatePermutation(char * , int , int );

int main()

char str[] = "ABC";

int n =strlen(str);

printf("All the permutations of the string are: \n");

generatePermutation(str,0,n);

//Function for generating different permutation of the string.

void generatePermutation(char *str,const int start, int end)

char temp;

int i,j;

for(i = start; i < end-1; ++i){


for(j = i+1; j < end; ++j)

//Swapping the string by fixing a character

temp = str[i];

str[i] = str[j];

str[j] = temp;

//Recursively calling function generatePermutation() for rest of the characters

generatePermutation(str , i+1 ,end);

//Backtracking and swapping the characters again

temp = str[i];

str[i] = str[j];

str[j] = temp;

//Print the permutations

printf("%s\n",str);

Output:

All the permutations of the string are:

ABC

ACB

BAC

BCA

CBA

CAB
5. Write a Program to store n students information using structure.

#include <stdio.h>

struct student {

char name[50];

int roll;

float marks;

} s;

int main() {

printf("Enter information:\n");

printf("Enter name: ");

fgets(s.name, sizeof(s.name), stdin);

printf("Enter roll number: ");

scanf("%d", &s.roll);

printf("Enter marks: ");

scanf("%f", &s.marks);

printf("Displaying Information:\n");

printf("Name: ");

printf("%s", s.name);

printf("Roll number: %d\n", s.roll);

printf("Marks: %.1f\n", s.marks);

return 0;

Output:

Enter information:
Enter name: Jack

Enter roll number: 23

Enter marks: 34.5

Displaying Information:

Name: Jack

Roll number: 23

Marks: 34.5

6. Write Program to implement Push, Pop and Traverse operation on STACK.

#include <stdio.h>

#include <stdlib.h>

#define SIZE 4

int top = -1, inp_array[SIZE];

void push();

void pop();

void show();

int main()

int choice;

while (1)

printf("\nPerform operations on the stack:");

printf("\n1.Push the element\n2.Pop the element\n3.Show\n4.End");

printf("\n\nEnter the choice: ");

scanf("%d", &choice);
switch (choice)

case 1:

push();

break;

case 2:

pop();

break;

case 3:

show();

break;

case 4:

exit(0);

default:

printf("\nInvalid choice!!");

void push()

int x;

if (top == SIZE - 1)

printf("\nOverflow!!");

}
else

printf("\nEnter the element to be added onto the stack: ");

scanf("%d", &x);

top = top + 1;

inp_array[top] = x;

void pop()

if (top == -1)

printf("\nUnderflow!!");

else

printf("\nPopped element: %d", inp_array[top]);

top = top - 1;

void show()

if (top == -1)

printf("\nUnderflow!!");
}

else

printf("\nElements present in the stack: \n");

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

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

Output:

10 pushed into stack

20 pushed into stack

30 pushed into stack

30 Popped from stack

Top element is : 20

Elements present in stack : 20 10

...........................................................

Process executed in 3.22 seconds

Press any key to continue.

7. Write Program to convert infix notation to postfix notation.

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

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+/

8. Write Program to convert Infix notation to prefix notation.

#include<stdio.h>

#include<string.h>

#include<limits.h>

#include<stdlib.h>
#define MAX 100

int top = -1;

char stack[MAX];

// checking if stack is full

int isFull ()

return top == MAX - 1;

// checking is stack is empty

int isEmpty ()

return top == -1;

void push (char item)

if (isFull ())

return;

top++;

stack[top] = item;

// Function to remove an item from stack. It decreases top by 1

int pop ()

if (isEmpty ())

return INT_MIN;
// decrements top and returns what has been popped

return stack[top--];

// Function to return the top from stack without removing it

int peek ()

if (isEmpty ())

return INT_MIN;

return stack[top];

// A utility function to check if the given character is operand

int checkIfOperand (char ch)

return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');

// Fucntion to compare precedence

// If we return larger value means higher precedence

int precedence (char ch)

switch (ch)

case '+':

case '-':

return 1;

case '*':
case '/':

return 2;

case '^':

return 3;

return -1;

// The driver function for infix to postfix conversion

int getPostfix (char *expression)

int i, j;

for (i = 0, j = -1; expression[i]; ++i)

if (checkIfOperand (expression[i]))

expression[++j] = expression[i];

else if (expression[i] == '(')

push (expression[i]);

else if (expression[i] == ')')

while (!isEmpty (stack) && peek (stack) != '(')

expression[++j] = pop (stack);

if (!isEmpty (stack) && peek (stack) != '(')

return -1; // invalid expression

else

pop (stack);
}

else // if an opertor

while (!isEmpty (stack)

&& precedence (expression[i]) <= precedence (peek (stack)))

expression[++j] = pop (stack);

push (expression[i]);

// Once all inital expression characters are traversed

// adding all left elements from stack to exp

while (!isEmpty (stack))

expression[++j] = pop (stack);

expression[++j] = '\0';

void reverse (char *exp)

int size = strlen (exp);

int j = size, i = 0;

char temp[size];

temp[j--] = '\0';

while (exp[i] != '\0')

temp[j] = exp[i];

j--;
i++;

strcpy (exp, temp);

void brackets (char *exp)

int i = 0;

while (exp[i] != '\0')

if (exp[i] == '(')

exp[i] = ')';

else if (exp[i] == ')')

exp[i] = '(';

i++;

void InfixtoPrefix (char *exp)

int size = strlen (exp);

// reverse string

reverse (exp);

//change brackets

brackets (exp);

//get postfix

getPostfix (exp);
// reverse string again

reverse (exp);

int main ()

printf ("The infix is: ");

char expression[] = "((a/b)+c)-(d+(e*f))";

printf ("%s\n", expression);

InfixtoPrefix (expression);

printf ("The prefix is: ");

printf ("%s\n", expression);

return 0;

Output:

The infix is: ((a/b)+c)-(d+(e*f))

The prefix is: -+/abc+d*ef

9. Write a program to convert Prefix notation to postfix notation.

/* C Program to convert prefix to postfix using stack */

#include<stdio.h>

#include<string.h>

#include<math.h>

#include<stdlib.h>
#define BLANK ' '

#define TAB '\t'

#define MAX 50

char *pop();

char prefix[MAX];

char stack[MAX][MAX];

void push(char *str);

int isempty();

int white_space(char symbol);

void prefix_to_postfix();

int top;

int main()

top = -1;

printf("Enter Prefix Expression : ");

gets(prefix);

prefix_to_postfix();

}/*End of main()*/

void prefix_to_postfix()

int i;
char operand1[MAX], operand2[MAX];

char symbol;

char temp[2];

char strin[MAX];

for(i=strlen(prefix)-1;i>=0;i--)

symbol=prefix[i];

temp[0]=symbol;

temp[1]='\0';

if(!white_space(symbol))

switch(symbol)

case '+':

case '-':

case '*':

case '/':

case '%':

case '^':

strcpy(operand1,pop());

strcpy(operand2,pop());

strcpy(strin,operand1);

strcat(strin,operand2);

strcat(strin,temp);
push(strin);

break;

default: /*if an operand comes*/

push(temp);

printf("\nPostfix Expression :: ");

puts(stack[0]);

}/*End of prefix_to_postfix()*/

void push(char *str)

if(top > MAX)

printf("\nStack overflow\n");

exit(1);

else

top=top+1;

strcpy( stack[top], str);

}/*End of push()*/
char *pop()

if(top == -1 )

printf("\nStack underflow \n");

exit(2);

else

return (stack[top--]);

}/*End of pop()*/

int isempty()

if(top==-1)

return 1;

else

return 0;

int white_space(char symbol)

if(symbol==BLANK || symbol==TAB || symbol=='\0')

return 1;

else

return 0;

}/*End of white_space()*/
Output:

/* C Program to convert prefix to postfix using stack */

Enter Prefix Expression : + + A * B C D

Postfix Expression :: ABC*+D+

Process returned 0

Enter Prefix Expression : / 10 5 = 2

Postfix Expression :: 2

Process returned 0

10. Write Program to perform the operation Insert, Delete and Display on Queue.

#include <stdio.h>

#include <conio.h>

#include <stdlib.h>

int q[25], n ,front=-1 , rear=-1 , item;

void insertion()

if((rear==n) && (front==(rear+1))||(front==rear+1))

printf(“\nQueue Overflow\n”);

}
else if (rear==0)

front = rear = 1;

else if(rear==n)

rear=1;

else

rear=rear+1;

printf(“Enter the item : “);

scanf(“%d”,&item);

q[rear] = item;

printf(“%d is inserted\n\n”,item);

void deletion()

if(front==0)

printf(“\nQueue Underflow\n\n”);

item=q[front];
if(front==rear)

front=0;

rear=0;

else if (front=n)

front=1;

else

front=front+1;

printf(“\n%d is deleted\n\n”,item);

void show()

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

printf(“%d\t”,q[i]);

}
int main()

int op;

printf(“Enter the size of the queue : “);

scanf(“%d”,&n);

do

printf(“\n1 : Insert”);

printf(“\n2 : Delete”);

printf(“\n3 : Print”);

printf(“\n4 : Exit”);

printf(“\nEnter your choice : “);

scanf(“%d”,&op);

switch(op)

case 1:

insertion();

break;

case 2:

deletion();

break;
case 3:

show();

break;

//default:

// printf(“Invalid Option. Try again.”);

}while(op!=4);

printf(“\n—THE END—\n”);

Output:
11. Write Program to implement Circular queue.

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

Output:
12. Write Program to implement Double ended queue.

#include <stdio.h>

#include <stdlib.h>

#define MAX 5 // Define maximum size of the deque

int deque[MAX];

int front = -1;


int rear = -1;

// Function to check if the deque is full

int isFull() {

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

// Function to check if the deque is empty

int isEmpty() {

return (front == -1);

// Function to insert an element at the front of the deque

void insertFront(int key) {

if (isFull()) {

printf("Overflow: Unable to insert element at the front. Deque is full.\n");

return;

if (front == -1) { // If deque is initially empty

front = 0;

rear = 0;

} else if (front == 0) {

front = MAX - 1; // wrap around

} else {

front = front - 1;

deque[front] = key;

printf("Inserted %d at the front.\n", key);


}

// Function to insert an element at the rear of the deque

void insertRear(int key) {

if (isFull()) {

printf("Overflow: Unable to insert element at the rear. Deque is full.\n");

return;

if (rear == -1) { // If deque is initially empty

front = 0;

rear = 0;

} else if (rear == MAX - 1) {

rear = 0; // wrap around

} else {

rear = rear + 1;

deque[rear] = key;

printf("Inserted %d at the rear.\n", key);

// Function to delete an element from the front of the deque

void deleteFront() {

if (isEmpty()) {

printf("Underflow: Unable to delete element from the front. Deque is empty.\n");

return;

int removed = deque[front];


if (front == rear) { // Deque has only one element

front = -1;

rear = -1;

} else if (front == MAX - 1) {

front = 0; // wrap around

} else {

front = front + 1;

printf("Deleted %d from the front.\n", removed);

// Function to delete an element from the rear of the deque

void deleteRear() {

if (isEmpty()) {

printf("Underflow: Unable to delete element from the rear. Deque is empty.\n");

return;

int removed = deque[rear];

if (front == rear) { // Deque has only one element

front = -1;

rear = -1;

} else if (rear == 0) {

rear = MAX - 1; // wrap around

} else {

rear = rear - 1;

}
printf("Deleted %d from the rear.\n", removed);

// Function to display the deque

void displayDeque() {

if (isEmpty()) {

printf("Deque is empty.\n");

return;

printf("Deque elements are: ");

int i = front;

while (1) {

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

if (i == rear)

break;

i = (i + 1) % MAX;

printf("\n");

// Main function to test the operations

int main() {

insertRear(5);

displayDeque();

insertFront(15);

displayDeque();

insertRear(25);
displayDeque();

deleteFront();

displayDeque();

deleteRear();

displayDeque();

return 0;

Output:

Inserted 5 at the rear.

Deque elements are: 5

Inserted 15 at the front.

Deque elements are: 15 5

Inserted 25 at the rear.

Deque elements are: 15 5 25

Deleted 15 from the front.

Deque elements are: 5 25

Deleted 25 from the rear.

Deque elements are: 5

13. Write Program to implement Priority queue.

#include <stdio.h>

#include <stdlib.h>

#define MAX 10

// Structure to represent a priority queue


struct PriorityQueue {

int heap[MAX];

int size;

};

// Function to initialize the priority queue

void init(struct PriorityQueue* pq) {

pq->size = 0;

// Function to swap two elements

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

int temp = *a;

*a = *b;

*b = temp;

// Function to heapify the tree at index i

void heapify(struct PriorityQueue* pq, int i) {

int largest = i;

int left = 2 * i + 1;

int right = 2 * i + 2;

if (left < pq->size && pq->heap[left] > pq->heap[largest])

largest = left;

if (right < pq->size && pq->heap[right] > pq->heap[largest])

largest = right;

if (largest != i) {

swap(&pq->heap[i], &pq->heap[largest]);
heapify(pq, largest);

// Function to insert an element into the priority queue

void insert(struct PriorityQueue* pq, int value) {

if (pq->size == MAX) {

printf("Priority Queue is full!\n");

return;

pq->heap[pq->size] = value;

int current = pq->size;

pq->size++;

// Move the newly added element to its correct position

while (current > 0 && pq->heap[(current - 1) / 2] < pq->heap[current]) {

swap(&pq->heap[current], &pq->heap[(current - 1) / 2]);

current = (current - 1) / 2;

// Function to delete the element with the highest priority

int delete(struct PriorityQueue* pq) {

if (pq->size == 0) {

printf("Priority Queue is empty!\n");

return -1;

int highest = pq->heap[0];


pq->heap[0] = pq->heap[pq->size - 1];

pq->size--;

// Heapify the root to maintain heap property

heapify(pq, 0);

return highest;

// Function to print the priority queue

void display(struct PriorityQueue* pq) {

if (pq->size == 0) {

printf("Priority Queue is empty!\n");

return;

printf("Priority Queue: ");

for (int i = 0; i < pq->size; i++) {

printf("%d ", pq->heap[i]);

printf("\n");

// Main function to test the priority queue implementation

int main() {

struct PriorityQueue pq;

init(&pq);

printf("Inserting elements into priority queue\n");

insert(&pq, 10);

insert(&pq, 20);
insert(&pq, 15);

insert(&pq, 30);

insert(&pq, 25);

display(&pq);

printf("\nDeleting highest priority element: %d\n", delete(&pq));

display(&pq);

printf("\nDeleting highest priority element: %d\n", delete(&pq));

display(&pq);

printf("\nInserting more elements into priority queue\n");

insert(&pq, 40);

insert(&pq, 5);

display(&pq);

return 0;

Output:

Inserting elements into priority queue

Priority Queue: 30 25 15 10 20

Deleting highest priority element: 30

Priority Queue: 25 20 15 10

Deleting highest priority element: 25

Priority Queue: 20 10 15

Inserting more elements into priority queue

Priority Queue: 40 20 15 10 5

14. Write a Program to search an element using Linear search.


#include <stdio.h>

int linearSearch(int arr[], int size, int target) {

for (int i = 0; i < size; i++) {

if (arr[i] == target) {

return i; // Element found, return its index

return -1; // Element not found

int main() {

int arr[] = {5, 3, 7, 2, 8, 9, 1};

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

int target = 8;

int result = linearSearch(arr, size, target);

if (result != -1)

printf("Element %d found at index %d\n", target, result);

else

printf("Element %d not found\n", target);

return 0;

}
Output:

Element 8 found at index 4

15. Write a Program to sort given Array using Insertion sort technique.

#include <stdio.h>

void insertionSort(int arr[], int size) {

for (int i = 1; i < size; i++) {

int key = arr[i];

int j = i - 1;

while (j >= 0 && arr[j] > key) {

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

j--;

arr[j + 1] = key;

void display(int arr[], int size) {

for (int i = 0; i < size; i++) {

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

printf("\n");

int main() {

int arr[] = {12, 11, 13, 5, 6};

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


printf("Original Array: ");

display(arr, size);

insertionSort(arr, size);

printf("Sorted Array: ");

display(arr, size);

return 0;

Output:

Original Array: 12 11 13 5 6

Sorted Array: 5 6 11 12 13

16. Write a Program to sort given Array using Bubble sort technique.

#include <stdio.h>

void bubbleSort(int arr[], int size) {

for (int i = 0; i < size - 1; i++) {

for (int j = 0; j < size - i - 1; j++) {

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

// Swap the elements

int temp = arr[j];

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

arr[j + 1] = temp;

}
void display(int arr[], int size) {

for (int i = 0; i < size; i++) {

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

printf("\n");

int main() {

int arr[] = {64, 34, 25, 12, 22, 11, 90};

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

printf("Original Array: ");

display(arr, size);

bubbleSort(arr, size);

printf("Sorted Array: ");

display(arr, size);

return 0;

Output:

Original Array: 64 34 25 12 22 11 90

Sorted Array: 11 12 22 25 34 64 90

17. Write a Program to sort given Array using Quick sort technique.

#include <stdio.h>

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

int temp = *a;


*a = *b;

*b = temp;

int partition(int arr[], int low, int high) {

int pivot = arr[high];

int i = (low - 1);

for (int j = low; j <= high - 1; j++) {

if (arr[j] < pivot) {

i++;

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

swap(&arr[i + 1], &arr[high]);

return (i + 1);

void quickSort(int arr[], int low, int high) {

if (low < high) {

int pi = partition(arr, low, high);

quickSort(arr, low, pi - 1);

quickSort(arr, pi + 1, high);

}
}

void display(int arr[], int size) {

for (int i = 0; i < size; i++) {

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

printf("\n");

int main() {

int arr[] = {10, 7, 8, 9, 1, 5};

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

printf("Original Array: ");

display(arr, size);

quickSort(arr, 0, size - 1);

printf("Sorted Array: ");

display(arr, size);

return 0;

Output:
Original Array: 10 7 8 9 1 5

Sorted Array: 1 5 7 8 9 10

18. Write a Program to sort given Array using selection sort technique.

#include <stdio.h>

void selectionSort(int arr[], int size) {

for (int i = 0; i < size - 1; i++) {

int minIdx = i;

for (int j = i + 1; j < size; j++) {

if (arr[j] < arr[minIdx]) {

minIdx = j;

// Swap the found minimum element with the element at index i

int temp = arr[i];

arr[i] = arr[minIdx];

arr[minIdx] = temp;

void display(int arr[], int size) {

for (int i = 0; i < size; i++) {

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

}
printf("\n");

int main() {

int arr[] = {64, 25, 12, 22, 11};

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

printf("Original Array: ");

display(arr, size);

selectionSort(arr, size);

printf("Sorted Array: ");

display(arr, size);

return 0;

Output:

Original Array: 64 25 12 22 11

Sorted Array: 11 12 22 25 64

19. Write Program to implement Singly Linked List.

#include <stdio.h>

#include <stdlib.h>
// Define a node of the linked list

struct Node {

int data;

struct Node* next;

};

// Function to insert a new node at the end

void insert(struct Node** head, int data) {

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

newNode->data = data;

newNode->next = NULL;

if (*head == NULL) {

*head = newNode;

} else {

struct Node* temp = *head;

while (temp->next != NULL) {

temp = temp->next;

temp->next = newNode;

// Function to display the linked list

void display(struct Node* head) {


struct Node* temp = head;

while (temp != NULL) {

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

temp = temp->next;

printf("NULL\n");

int main() {

struct Node* head = NULL;

insert(&head, 10);

insert(&head, 20);

insert(&head, 30);

printf("Singly Linked List: ");

display(head);

return 0;

Output:

Singly Linked List: 10 -> 20 -> 30 -> NULL

20. Write Program to implement Double Linked List.

#include <stdio.h>

#include <stdlib.h>

// Define a node of the doubly linked list

struct Node {

int data;
struct Node* prev;

struct Node* next;

};

// Function to insert a new node at the end

void insert(struct Node** head, int data) {

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

newNode->data = data;

newNode->next = NULL;

newNode->prev = NULL;

if (*head == NULL) {

*head = newNode;

} else {

struct Node* temp = *head;

while (temp->next != NULL) {

temp = temp->next;

temp->next = newNode;

newNode->prev = temp;

// Function to display the doubly linked list

void display(struct Node* head) {

struct Node* temp = head;

while (temp != NULL) {

printf("%d <-> ", temp->data);


temp = temp->next;

printf("NULL\n");

int main() {

struct Node* head = NULL;

insert(&head, 10);

insert(&head, 20);

insert(&head, 30);

printf("Doubly Linked List: ");

display(head);

return 0;

Output:

Doubly Linked List: 10 <-> 20 <-> 30 <-> NULL

You might also like