Dsa Assignment Final Ojas Nagta 102184009
Dsa Assignment Final Ojas Nagta 102184009
Dsa Assignment Final Ojas Nagta 102184009
A
Laboratory File
Submitted For
Submitted By:
Ojas Nagta
102184009
3EE4
Submitted To:
Dr. Ashish Kumar Gupta
A DEEMED TO BE UNIVERSITY)
PATIALA, PUNJAB-147004
INDEX
1. 3-13
Assignment 1
2. 14-28
Assignment 2
3. 29-33
Assignment 3
4. 34-40
Assignment 4
5. 41-53
Assignment 5
6. Assignment 6 54-57
7 Assignment 7 58-64
8 Assignment 8 65-67
9 Assignment 9 68-78
Code:
#include <stdio.h>
#define MILES_TO_KM 1.609
void convert_miles_to_km() {
float miles, km;
printf("Enter distance in miles: ");
scanf("%f", &miles);
km = miles * MILES_TO_KM;
printf("%.2f miles = %.2f kilometers\n", miles, km);
}
int main() {
convert_miles_to_km();
return 0; }
Output:
Que :2) Write a program to find the number of positive, negative and
zeros in a sequence of inputs (numbers) entered as data
Code:
#include <stdio.h>
void count_positive_negative_zero() {
int num, positive = 0, negative = 0, zero = 0;
printf("Enter a sequence of numbers (-999 to end):\n");
do {
scanf("%d", &num);
if (num == -999) {
break; // stop loop when -999 is entered
} else if (num > 0) {
positive++;
} else if (num < 0) {
negative++;
} else {
zero++; }
} while (1);
printf("Positive numbers: %d\n", positive);
printf("Negative numbers: %d\n", negative);
printf("Zeros: %d\n", zero);
int main() { count_positive_negative_zero();
return 0;}
int choice;
do { printf("\nArea Calculator Menu\n");
printf("1. Square\n");
printf("2. Rectangle\n");
printf("3. Circle\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
calculate_area_of_square();
break;
case 2:
calculate_area_of_rectangle();
break;
case 3:
calculate_area_of_circle();
break;
case 4:
printf("Exiting...\n");
break;
default:
printf("Invalid choice. Try again.\n");
break; }
} while (choice!= 4);
return 0;
}
void calculate_area_of_square() {
float side, area;
printf("Enter the length of a side of the square: ");
scanf("%f", &side);
area = side * side;
Output:
#include <stdio.h>
int main() {
int x, y, i, j;
printf("Enter the starting table number: ");
scanf("%d", &x);
printf("Enter the ending table number: ");
scanf("%d", &y);
printf("\n");
for (i = 1; i <= 10; i++) {
for (j = x; j <= y; j++) {
printf("%4d x %2d = %3d ", j, i, i * j); }
printf("\n");
} return 0;}
Output:
Output:
Output:
Que: 9) Write a function that returns the first integer between n_min
and n_max entered as data to the calling function (main).
Code:
#include <stdio.h>
#include <stdlib.h>
int random_int(int min, int max)
{ return min + rand() % (max - min + 1);}
int first_int(int n_min, int n_max)
{
int num;
printf("Enter an integer between %d and %d: ", n_min, n_max);
scanf("%d", &num);
while (num < n_min || num > n_max)
{
printf("Invalid input. Try again: ");
scanf("%d", &num); }
return num;}
int main(){
int n_min = 10;
int n_max = 20;
int result = first_int(n_min, n_max);
printf("The first integer between %d and %d is %d\n", n_min, n_max, result);
return 0;}
Output:
Que: 10) Write nests of loops that cause the following output to be
displayed.
Code:
#include<bits/stdc++.h>
using namespace std;
void len_ser(int a[],int n)
{
int x;
cout<<"input target element:"<<endl;
cin>>x;
for(int i=0;i<n;i++)
{
if(a[i]==x)
{
cout<<"element is found at index:"<<i;
}
}
}
int main()
{
int i,n;
cout<<"Enter n"<<endl;
cin>>n;
int a[n];
cout<<"enter elemnts of array"<<endl;
for(i=0;i<n;i++)
{
cin>>a[i];
}
cout<<"array"<<endl;
for(i=0;i<n;i++)
{
cout<<" "<<a[i];
}
cout<<endl;
len_ser(a,n);
return 0;
}
max2=INT_MIN;
for(int i=0;i<n;i++)
{
if(a[i]==max1) continue;
max2=max(max2,a[i]);
}
cout<<"Second max is:"<<max2<<endl;
cout<<"Second min is:"<<min2<<endl;
}
int main()
{ int i,n;
cout<<"Enter n"<<endl;
cin>>n;
int a[n];
cout<<"enter elemnts of array"<<endl;
for(i=0;i<n;i++)
{
cin>>a[i];
}
cout<<"array"<<endl;
for(i=0;i<n;i++)
{
cout<<" "<<a[i];
}
cout<<endl;
max_min(a,n);
return 0;}
#include<bits/stdc++.h>
using namespace std;
void traverse(int [],int);
void insertion(int [],int);
void deletion(int [],int);
int main()
{
int i,n;
cout<<"Enter n"<<endl;
cin>>n;
int a[n];
cout<<"enter elemnts of array"<<endl;
for(i=0;i<n;i++)
{
cin>>a[i];
}
int fun;
cout<<endl;
cout<<"write operation to perform:"<<endl;
cin>>fun;
switch(fun){
case 1:
traverse(a,n);
break;
case 2:
insertion(a,n);
break;
case 3:
deletion(a,n);
break;;
default:
cout<<"No operation selected:"<<endl;
}
}
traverse(a,n);
}
void deletion(int a[],int n)
{
int x;
cout<<"Enter loction:"<<endl;
cin>>x;
for (int i = x - 1; i < n- 1; i++)
{
a[i] = a[i+1];
}
n--;
traverse(a,n);}
int main() {
int size, choice;
int arr1[MAX_SIZE], arr2[MAX_SIZE], result[MAX_SIZE];
while (true) {
cout << "Menu" << endl;
cout << "1. Add arrays" << endl;
cout << "2. Multiply arrays" << endl;
cout << "3. Subtract arrays" << endl;
cout << "4. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
add_arrays(arr1, arr2, size, result);
cout << "Result of addition: ";
display_array(result, size);
break;
case 2:
multiply_arrays(arr1, arr2, size, result);
cout << "Result of multiplication: ";
display_array(result, size);
break;
case 3:
subtract_arrays(arr1, arr2, size, result);
cout << "Result of subtraction: ";
display_array(result, size);
break;
case 4:
exit(0);
default:
cout << "Invalid choice. Try again." << endl;
}
}
return 0;
}
#include <bits/stdc++.h>
using namespace std;
void merge(int arr1[], int n1, int arr2[], int n2, int result[]) {
int i = 0;
int j = 0;
int k = 0;
int main() {
int arr1[5];
int arr2[5];
int n1 = 5;
int n2 = 5;
int result[n1 + n2];
return 0;
}
cin >> n;
int a[n];
cout << "Enter elements of array: " << endl;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
int x, idx;
cout << "Input target element: " << endl;
cin >> x;
len_ser(a, n, x, idx);
if (idx == -1) {
cout << "Element not found in array" << endl;
} else {
cout << "Element found at index " << idx << endl;
}
return 0;}
Que 2:
#include<bits/stdc++.h>
using namespace std;
cout<<endl;
max_min(a,n);
return 0;
}
Que 3:
#include<bits/stdc++.h>
using namespace std;
void traverse(int *, int);
void insertion(int *, int&);
void deletion(int *, int&);
int main()
{
int n;
cout << "Enter n: " << endl;
cin >> n;
int a[n];
cout << "Enter elements of array: " << endl;
for(int i=0;i<n;i++)
{
cin >> a[i];
}
int fun;
cout << endl << "Write operation to perform: " << endl;
cin >> fun;
switch(fun)
{ case 1:
traverse(a,n);
break;
case 2:
insertion(a,n);
break;
case 3:
deletion(a,n);
break;
default:
cout << "No operation selected." << endl;
}}
void traverse(int *a, int n)
{
cout << "Array: " << endl;
for(int i=0;i<n;i++)
{
cout << " " << *(a+i);
}
cout << endl;
}
void insertion(int *a, int &n)
{ int x, pos;
cout << "Enter element: ";
cin >> x;
cout << "Enter location: ";
cin >> pos;
for(int i=n-1; i>=pos; i--)
{
*(a+i+1) = *(a+i);
}
*(a+pos) = x;
n++;
traverse(a, n);
}
void deletion(int *a, int &n)
{ int x;
cout << "Enter location: " << endl;
cin >> x;
for(int i=x-1; i<n-1; i++)
{
*(a+i) = *(a+i+1);
}
n--;
traverse(a,n); }
Assignment – 3
Que 1: Write a program to implement strlen() function
Code:
#include <iostream>
using namespace std;
int strlen(char* str) {
int length = 0;
while (*str != '\0') {
length++;
str++;
}
return length;
}
int main() {
char str[] = "Hello, world!";
int length = strlen(str);
cout << "The length of the string is: " << length << endl;
return 0;
}
Output:
*dest = *src;
dest++;
src++;
}
*dest = '\0';
return ptr;
}
int main() {
// Test the strcpy() function
char str1[20] = "Hello";
char str2[20];
strcpy(str2, str1);
cout << "Copied string is: " << str2 << endl;
return 0;
}
Output:
Output:
Output:
Assignment – 4
Que 1: Write a program to implement KMP pattern matching algorithm.
[String processing]
Code:
#include <bits/stdc++.h>
i++;
}
else
{
if (len != 0) {
len = lps[len - 1];
}
else
{
lps[i] = 0;
i++;
}
}
}
}
int main()
{
char txt[] = "ABABDABACDABABCABAB";
char pat[] = "ABABCABAB";
KMPSearch(pat, txt);
return 0;
}
Output:
}
int sumRecursive(int arr[], int n){
if(n == 0){
return 0;
}
else{
return arr[n-1] + sumRecursive(arr, n-1);
}
}
int main(){
int n;
cout<<"Enter the number of elements: ";
cin>>n;
int arr[n];
cout<<"Enter the elements: ";
for(int i=0; i<n; i++){
cin>>arr[i];
}
cout<<"Sum using iterative approach: "<<sumIterative(arr, n)<<endl;
cout<<"Sum using recursive approach: "<<sumRecursive(arr, n)<<endl;
return 0;
}
Output:
if (arr[mid] == target) {
return mid;
}
else if (arr[mid] < target) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
return -1;
}
int binarySearchRecursive(vector<int> arr, int target, int left, int right) {
if (left > right) {
return -1;
}
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
}
else if (arr[mid] < target) {
return binarySearchRecursive(arr, target, mid + 1, right);
}
else {
return binarySearchRecursive(arr, target, left, mid - 1);
}
}
int main() {
vector<int> arr = {1, 3, 5, 7, 9};
int target = 5;
int indexIterative = binarySearchIterative(arr, target);
if (indexIterative == -1) {
cout << "Target not found using iterative approach" << endl;
}
else {
cout << "Target found at index " << indexIterative << " using iterative approach" << endl;
}
int indexRecursive = binarySearchRecursive(arr, target, 0, arr.size() - 1);
if (indexRecursive == -1) {
cout << "Target not found using recursive approach" << endl;
}
else {
cout << "Target found at index " << indexRecursive << " using recursive approach" << endl;
}
return 0;
}
Result:
Result:
Que 5: Write a program to implement finding min and max from an array. a)
Iterative approach b) Recursive approach.
Code:
#include <iostream>
#include <climits>
using namespace std;
void findMinMaxIterative(int arr[], int n, int& min, int& max) {
min = arr[0];
max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] < min) {
min = arr[i];
}
if (arr[i] > max) {
max = arr[i];
}
}
}
void findMinMaxRecursive(int arr[], int low, int high, int& min, int& max) {
if (low == high) {
min = arr[low];
max = arr[low];
return;
}
if (high == low + 1) {
if (arr[low] < arr[high]) {
min = arr[low];
max = arr[high];
} else {
min = arr[high];
max = arr[low];
}
return;
}
int mid = (low + high) / 2;
int min1, max1, min2, max2;
findMinMaxRecursive(arr, low, mid, min1, max1);
findMinMaxRecursive(arr, mid + 1, high, min2, max2);
min = (min1 < min2) ? min1 : min2;
max = (max1 > max2) ? max1 : max2;
}
int main() {
int arr[] = { 1, 4, 6, 2, 8, 3, 9, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
int minIterative, maxIterative;
findMinMaxIterative(arr, n, minIterative, maxIterative);
cout << "Minimum element using iterative approach: " << minIterative << endl;
cout << "Maximum element using iterative approach: " << maxIterative << endl;
int minRecursive, maxRecursive;
findMinMaxRecursive(arr, 0, n - 1, minRecursive, maxRecursive);
cout << "Minimum element using recursive approach: " << minRecursive << endl;
cout << "Maximum element using recursive approach: " << maxRecursive << endl;
return 0;
}
Output:
Assignment – 5
Program: 01 Write a menu driven program with 4 options
(Push, Pop, Display, and Exit) to demonstrate the working of
stacks using arrays.
#include <iostream>
using namespace std;
#define MAX_SIZE 10
int pop() {
if (top == -1) {
cout << "Stack Underflow!" << endl;
return -1;
} else {
int popped_item = stack[top];
top--;
cout << popped_item << " popped from stack." << endl;
return popped_item;
}
}
void display() {
if (top == -1) {
cout << "Stack is empty." << endl;
} else {
cout << "Elements in stack are: ";
for (int i = top; i >= 0; i--) {
cout << stack[i] << " ";
}
int main() {
int choice, item;
while (true) {
cout << endl;
cout << "Stack Operations" << endl;
cout << "1. Push" << endl;
cout << "2. Pop" << endl;
cout << "3. Display" << endl;
cout << "4. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter item to push: ";
cin >> item;
push(item);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
cout << "Exiting program..." << endl;
exit(0);
default:
cout << "Invalid choice, please try again." << endl;
}
}
return 0;
}
Output:
struct Node {
int data;
Node* next;
};
class Stack {
Node* top;
public:
Stack() {
top = NULL;
}
int pop() {
if (top == NULL) {
cout << "Stack Underflow!" << endl;
return -1;
}
int popped_item = top->data;
Node* temp = top;
top = top->next;
delete temp;
cout << popped_item << " popped from stack." << endl;
return popped_item;
}
void display() {
if (top == NULL) {
cout << "Stack is empty." << endl;
return;
}
cout << "Elements in stack are: ";
Node* temp = top;
int main() {
Stack stack;
int choice, item;
while (true) {
cout << "Stack Operations" << endl;
cout << "1. Push" << endl;
cout << "2. Pop" << endl;
cout << "3. Display" << endl;
cout << "4. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter item to push: ";
cin >> item;
stack.push(item);
break;
case 2:
stack.pop();
break;
case 3:
stack.display();
break;
case 4:
cout << "Exiting program..." << endl;
exit(0);
default:
cout << "Invalid choice, please try again." << endl;
}
}
return 0;
}
Output:
struct Node {
int data;
Node* next;
};
class Queue {
Node* front;
Node* rear;
public:
Queue() {
front = NULL;
rear = NULL;
}
void insert(int item) {
Node* new_node = new Node;
new_node->data = item;
new_node->next = NULL;
if (front == NULL) {
front = rear = new_node;
} else {
rear->next = new_node;
rear = new_node;
}
cout << item << " inserted into queue." << endl;
}
int delete_item() {
if (front == NULL) {
cout << "Queue is empty!" << endl;
return -1;
}
int deleted_item = front->data;
Node* temp = front;
front = front->next;
delete temp;
cout << deleted_item << " deleted from queue." << endl;
return deleted_item;
}
void display() {
if (front == NULL) {
cout << "Queue is empty!" << endl;
return;
}
cout << "Elements in queue are: ";
Node* temp = front;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}};
int main() {
Queue queue;
int choice, item;
while (true) {
cout << "Queue Operations" << endl;
cout << "1. Insert" << endl;
cout << "2. Delete" << endl;
cout << "3. Display" << endl;
cout << "4. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter item to insert: ";
cin >> item;
queue.insert(item);
break;
case 2:
queue.delete_item();
break;
case 3:
queue.display();
break;
case 4:
cout << "Exiting program..." << endl;
exit(0);
default:
cout << "Invalid choice, please try again." << endl;
} }
return 0;
}
Output:
class CircularQueue {
int* arr;
int front;
int rear;
int size;
public:
CircularQueue(int s) {
arr = new int[s];
front = -1;
rear = -1;
size = s;
}
int is_empty() {
return front == -1;
}
int is_full() {
return (front == 0 && rear == size - 1) || (rear == front - 1);
}
int delete_item() {
if (is_empty()) {
cout << "Queue is empty!" << endl;
return -1;
}
int deleted_item = arr[front];
if (front == rear) {
front = rear = -1;
} else if (front == size - 1) {
front = 0;
} else {
front++;
}
cout << deleted_item << " deleted from queue." << endl;
return deleted_item;
}
void display() {
if (is_empty()) {
cout << "Queue is empty!" << endl;
return;
}
cout << "Elements in queue are: ";
if (rear >= front) {
for (int i = front; i <= rear; i++) {
cout << arr[i] << " ";
}
} else {
for (int i = front; i < size; i++) {
cout << arr[i] << " ";
}
for (int i = 0; i <= rear; i++) {
cout << arr[i] << " ";
}
}
cout << endl;
}
};
int main() {
int size, choice, item;
cout << "Enter size of circular queue: ";
cin >> size;
CircularQueue queue(size);
while (true) {
cout << "Circular Queue Operations" << endl;
cout << "1. Insert" << endl;
cout << "2. Delete" << endl;
cout << "3. Display" << endl;
cout << "4. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter item to insert: ";
cin >> item;
queue.insert(item);
break;
case 2:
queue.delete_item();
break;
case 3:
queue.display();
break;
case 4:
cout << "Exiting program..." << endl;
exit(0);
default:
cout << "Invalid choice, please try again." << endl;
}
}
return 0;
}
Output:
Assignment – 6
Que :1 Write a program to convert infix expression into postfix expression
using stack
Code:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
string infixToPostfix(string infix) {
stack<char> s;
string postfix = "";
for (char c : infix) {
if (isalnum(c)) {
postfix += c;
}
else if (c == '(') {
s.push(c);
}
else if (c == ')') {
while (!s.empty() && s.top() != '(') {
postfix += s.top();
s.pop();
}
s.pop();
}
else {
while (!s.empty() && s.top() != '(' && ((c == '*' || c == '/') && (s.top() == '+' || s.top() == '-') || (c
== s.top() && (c == '+' || c == '-')))) {
postfix += s.top();
s.pop();
}
s.push(c);
}
}
while (!s.empty()) {
postfix += s.top();
s.pop();
}
return postfix;
}
int main() {
string infix = "a+b*c-d/e";
string postfix = infixToPostfix(infix);
Result:
if (!stack)
return NULL;
stack->top = -1;
stack->capacity = capacity;
stack->array
= (int*)malloc(stack->capacity * sizeof(int));
if (!stack->array)
return NULL;
return stack;
}
int isEmpty(struct Stack* stack)
{
return stack->top == -1;
}
int peek(struct Stack* stack)
{
return stack->array[stack->top];
}
int pop(struct Stack* stack)
{
if (!isEmpty(stack))
return stack->array[stack->top--];
return '$';
}
void push(struct Stack* stack, int op)
{
stack->array[++stack->top] = op;
}
int evaluatePostfix(char* exp)
{
struct Stack* stack = createStack(strlen(exp));
int i;
if (!stack)
return -1;
for (i = 0; exp[i]; ++i) {
if (exp[i] == ' ')
continue;
else if (isdigit(exp[i])) {
int num = 0;
while (isdigit(exp[i])) {
num = num * 10 + (int)(exp[i] - '0');
i++;
}
i--;
push(stack, num);
}
else {
int val1 = pop(stack);
int val2 = pop(stack);
switch (exp[i]) {
case '+':
push(stack, val2 + val1);
break;
case '-':
push(stack, val2 - val1);
break;
case '*':
push(stack, val2 * val1);
break;
case '/':
Output:
Assignment – 7
Que 1: Write a program to implement bubble sort for sorting n elements in an
array
Code:
#include <iostream>
using namespace std;
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void bubbleSort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
swap(&arr[j], &arr[j + 1]);
}
}
}
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
int main()
{
int n;
cout << "Enter the size of the array: ";
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cout << "Enter element " << i + 1 << ": ";
cin >> arr[i];
}
cout << "The array is: ";
for (int i = 0; i < n; i++)
{
Result:
int arr[n];
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
selectionSort(arr, n);
cout << "Sorted array is: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
Output:
int n;
cout << "Enter the number of elements in the array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
insertionSort(arr, n);
cout << "Sorted array is: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
Output:
}
int main() {
int n;
cout << "Enter the number of elements in the array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
shellSort(arr, n);
Result:
Code:
Ojas Nagta 102184009
63
#include <iostream>
using namespace std;
int getMax(int arr[], int n) {
int mx = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > mx) {
mx = arr[i];
}
}
return mx;
}
void countSort(int arr[], int n, int exp) {
int output[n];
int i, count[10] = {0};
for (i = 0; i < n; i++) {
count[(arr[i] / exp) % 10]++;
}
for (i = 1; i < 10; i++) {
count[i] += count[i - 1];
}
for (i = n - 1; i >= 0; i--) {
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
}
}
return 0;
}
Result:
Assignment – 8
Que 1: Write a program to implement Merge sort.
Code:
#include <iostream>
using namespace std;
void merge(int arr[], int l, int m, int r) {
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++) {
L[i] = arr[l + i];
}
for (j = 0; j < n2; j++) {
R[j] = arr[m + 1 + j];
}
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
Result:
Output:
Assignment – 9
Que 1: Write a program to implement single Link List (with function insertion
at first node, insertion at last node, deletion at first node, deletion at last node,
insertion and deletion at middle node and traversing of link list).
Code:
#include <iostream>
if (head == NULL) {
cout << "Linked list is empty" << endl;
return;
}
Node* temp = head;
head = head->next;
delete temp;
}
void deleteAtLast() {
if (head == NULL) {
cout << "Linked list is empty" << endl;
return;
}
if (head->next == NULL) {
delete head;
head = NULL;
return;
}
Node* temp = head;
while (temp->next->next != NULL) {
temp = temp->next;
}
delete temp->next;
temp->next = NULL;
}
void insertAtMiddle(int data, int position) {
Node* newNode = new Node;
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
return;
}
Node* temp = head;
for (int i = 1; i < position-1 && temp != NULL; i++) {
temp = temp->next;
}
if (temp == NULL) {
cout << "Position out of range" << endl;
return;
}
newNode->next = temp->next;
temp->next = newNode;
}
void deleteAtMiddle(int position) {
if (head == NULL) {
cout << "Linked list is empty" << endl;
return;
}
Node* temp = head;
Node* prev = NULL;
for (int i = 1; i < position && temp != NULL; i++) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
cout << "Position out of range" << endl;
return;
}
if (prev == NULL) {
head = temp->next;
} else {
prev->next = temp->next;
}
delete temp;
}
void traverse() {
if (head == NULL) {
cout << "Linked list is empty" << endl;
return;
}
Node* temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
int main() {
LinkedList list;
list.insertAtFirst(10);
list.insertAtFirst(20);
list.insertAtLast(30);
list.insertAtLast(40);
list.insertAtMiddle(50, 3);
list.traverse();
list.deleteAtFirst();
list.deleteAtLast();
list.deleteAtMiddle(2);
list.traverse();
return 0;
}
Output:
newNode->prev = tail;
newNode->next = NULL;
if (tail != NULL) {
tail->next = newNode;
}
tail = newNode;
if (head == NULL) {
head = newNode;
}
}
void deleteAtFirst() {
if (head == NULL) {
cout << "List is empty" << endl;
return;
}
Node* temp = head;
head = head->next;
if (head != NULL) {
head->prev = NULL;
}
delete temp;
}
void deleteAtLast() {
if (tail == NULL) {
cout << "List is empty" << endl;
return;
}
Node* temp = tail;
tail = tail->prev;
if (tail != NULL) {
tail->next = NULL;
}
delete temp;
}
void insertAtMiddle(int value, int position) {
Node* newNode = new Node;
newNode->data = value;
Node* temp = head;
for (int i = 1; i < position && temp != NULL; i++) {
temp = temp->next;
}
if (temp == NULL) {
cout << "Invalid position" << endl;
return;
}
newNode->prev = temp;
newNode->next = temp->next;
if (temp->next != NULL) {
temp->next->prev = newNode;
}
temp->next = newNode;
}
void deleteAtMiddle(int position) {
Node* temp = head;
for (int i = 1; i < position && temp != NULL; i++) {
temp = temp->next;
}
if (temp == NULL) {
cout << "Invalid position" << endl;
return;
}
if (temp == head) {
head = temp->next;
}
if (temp == tail) {
tail = temp->prev;
}
if (temp->prev != NULL) {
temp->prev->next = temp->next;
}
if (temp->next != NULL) {
temp->next->prev = temp->prev;
}
delete temp;
}
void traverse() {
Node* temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
int main() {
DoublyLinkedList dll;
dll.insertAtFirst(10);
dll.insertAtFirst(20);
dll.insertAtFirst(30);
dll.traverse();
dll.insertAtLast(40);
dll.insertAtLast(50);
dll.insertAtLast(60);
dll.traverse();
dll.deleteAtFirst();
dll.deleteAtFirst();
dll.traverse();
dll.deleteAtLast();
dll.deleteAtLast();
dll.traverse();
dll.insertAtMiddle(30, 2);
dll.insertAtMiddle(50, 3);
dll.traverse();
dll.deleteAtMiddle(2);
dll.deleteAtMiddle(2);
dll.traverse();
return 0;
}
Result:
deletion at last node, insertion and deletion at middle node and traversing of link
list).
Code:
#include <iostream>
using namespace std;
struct Node {
int data;
Node* prev;
Node* next;
};
class DoublyLinkedList {
private:
Node* head;
Node* tail;
public:
DoublyLinkedList() {
head = NULL;
tail = NULL;
}
void insertAtFirst(int value) {
Node* newNode = new Node;
newNode->data = value;
newNode->prev = NULL;
newNode->next = head;
if (head != NULL) {
head->prev = newNode;
}
head = newNode;
if (tail == NULL) {
tail = newNode;
}
}
void insertAtLast(int value) {
Node* newNode = new Node;
newNode->data = value;
newNode->prev = tail;
newNode->next = NULL;
if (tail != NULL) {
tail->next = newNode;
}
tail = newNode;
if (head == NULL) {
head = newNode;
}
}
void deleteAtFirst() {
if (head == NULL) {
}
if (temp == head) {
head = temp->next;
}
if (temp == tail) {
tail = temp->prev;
}
if (temp->prev != NULL) {
temp->prev->next = temp->next;
}
if (temp->next != NULL) {
temp->next->prev = temp->prev;
}
delete temp;
}
void traverse() {
Node* temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
int main() {
DoublyLinkedList dll;
dll.insertAtFirst(10);
dll.insertAtFirst(20);
dll.insertAtFirst(30);
dll.traverse();
dll.insertAtLast(40);
dll.insertAtLast(50);
dll.insertAtLast(60);
dll.traverse();
dll.deleteAtFirst();
dll.deleteAtFirst();
dll.traverse();
dll.deleteAtLast();
dll.deleteAtLast();
dll.traverse();
dll.insertAtMiddle(30, 2);
dll.insertAtMiddle(50, 3);
dll.traverse();
dll.deleteAtMiddle(2);
dll.deleteAtMiddle(2);
dll.traverse();
return 0;
}
Output: