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

Ali Irtza Haider-231259-Linked List

linked lists

Uploaded by

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

Ali Irtza Haider-231259-Linked List

linked lists

Uploaded by

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

Lab Task 5

DSA LAB
Submitted To: Mr. Abdullah Imran
Submitted By: Ali Irtza Haider (231259)
BSCYS-3-B-F23
Linked List
Code:
#include <iostream>
struct Node {
int data = 0;
Node* next = nullptr;

Node(int _d = 0) : data(_d) {}
};

// seq
class LinkedList {
public:
Node* head = nullptr;
int size = 0;
LinkedList() {}
LinkedList(int data) {
if (data) {
head = new Node(data);
++size;
}
}

// destructor
~LinkedList() {
if (!head) return;
Node* tmp = head;
Node* prev = head;
while (tmp) {
prev = tmp;
tmp = tmp->next;
delete prev;
prev = nullptr;
}
delete tmp;
tmp = nullptr;
}
void insert_at_tail(int data) {
Node* node = new Node(data);
if (!head) {
head = node;
}
else {
Node* temp = head;
while (temp->next)
temp = temp->next;
temp->next = node;
}
++size;
}

void insert_at_head(int data) {


Node* node = new Node(data);
if (!head)
head = node;
else {
node->next = head;
head = node;
}
++size;
}

void print() {
Node* tmp = head;
while (tmp) {
std::cout << tmp->data;
if (tmp->next) {
std::cout << ", ";
}
tmp = tmp->next;
}
std::cout << "\n";
delete tmp;
}

int insert_at_idx(int idx, int data) {

if (idx < 0 || idx > size) {


return 127;
}
Node* newNode = new Node(data);

if (idx == 0) {
newNode->next = head;
head = newNode;
}
else {
Node* temp = head;
for (int i = 1; i < idx; ++i) {
temp = temp->next;
}
newNode->next = temp->next;
temp->next = newNode;
}

++size;
return 0;
}
};

Output:

You might also like