0% found this document useful (0 votes)
8 views4 pages

ID 2023200010118 Insert

Uploaded by

pial.nayeem
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)
8 views4 pages

ID 2023200010118 Insert

Uploaded by

pial.nayeem
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/ 4

Insert-Assignment - 3

Faculty Initial : MRT

Faculty Name : Mr. Raihan Tanvir

Course Code and : CSE242.25


Section

Course Title : Data Structure Lab

Program : B. Sc. in CSE (Diploma Students)

Department : Computer Science and Engineering

Semester : Fall 2024

Assignment : 04-01-2025
Posted on

Assignment : 10-01-2025
Submission Date

Submitted By

Name : Md. Jakariya

Student Code : 2 0 2 3 2 0 0 0 1 0 1 1 8
#include <iostream>
using namespace std;

struct Node {
int data;
Node* next;
Node(int val) : data(val), next(nullptr) {}
};

void printList(Node* head) {


Node* temp = head;
while (temp) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;
}

void append(Node*& head, int val) {


Node* newNode = new Node(val);
if (!head) {
head = newNode;
return;
}
Node* temp = head;
while (temp->next) {
temp = temp->next;
}
temp->next = newNode;
}

void insertInMiddleByPosition(Node*& head, int val) {


if (!head) {
head = new Node(val);
return;
}

int count = 0;
Node* temp = head;
while (temp) {
count++;
temp = temp->next;
}

int mid = count / 2;

temp = head;
for (int i = 1; i < mid; i++) {
temp = temp->next;
}

Node* newNode = new Node(val);


newNode->next = temp->next;
temp->next = newNode;
}

void insertInMiddleTwoPointers(Node*& head, int val) {


if (!head) {
head = new Node(val);
return;
}

Node *slow = head, *fast = head;


Node* prev = nullptr;

while (fast && fast->next) {


prev = slow;
slow = slow->next;
fast = fast->next->next;
}

Node* newNode = new Node(val);


newNode->next = slow;
if (prev) {
prev->next = newNode;
} else {
head = newNode;
}
}

int main() {
Node* head = nullptr;

append(head, 1);
append(head, 2);
append(head, 3);
append(head, 4);
append(head, 5);

cout << "Original List: ";


printList(head);

insertInMiddleByPosition(head, 99);
cout << "After inserting 99 (By Position): ";
printList(head);
insertInMiddleTwoPointers(head, 42);
cout << "After inserting 42 (Using Two Pointers): ";
printList(head);

return 0;
}

You might also like