LAB 3 Graded Task
LAB 3 Graded Task
Subject: DSA
Course instructor: Mam Marwa
Reg no: FA23-BCS-167
Name: Hamza
Code:
Task 1: Task 2:
#include <iostream> #include <iostream>
using namespace std; using namespace std;
class Node { class Node {
public: public:
int data; int data;
Node* next; Node* next;
Node* prev; Node* prev;
Node(int val) : data(val), next(nullptr), prev(nullptr) {} Node(int val) : data(val), next(nullptr), prev(nullptr) {}
}; };
public: public:
DoublyLinkedList() : head(nullptr) {} DoublyLinkedList() : head(nullptr) {}
dll.swapNodes(val1, val2);
return 0;
}
Task 3:
#include <iostream>
using namespace std;
Dry Run:
class Node { This code converts sll to dll the function has given a single link
public: list as argument and first the head is copied into double link list
int data; and loop starts from next to head of single link list
Node* next; and copies the data into dll finally the the list is displayed
Node* prev; through print list function;
Node(int val) : data(val), next(nullptr), prev(nullptr) {}
};
class SinglyLinkedList {
public:
Node* head;
SinglyLinkedList() : head(nullptr) {}
void insert(int val) {
Node* newNode = new Node(val);
if (!head) {
head = newNode;
return;
}
Node* temp = head;
while (temp->next) {
temp = temp->next;
}
temp->next = newNode;
}
};
class DoublyLinkedList {
public:
Node* head;
DoublyLinkedList() : head(nullptr) {}
void convertFromSingly(SinglyLinkedList& sll) {
if (!sll.head) return;
head = new Node(sll.head->data);
Node* sllTemp = sll.head->next;
Node* dllTemp = head;
while (sllTemp) {
Node* newNode = new Node(sllTemp->data);
dllTemp->next = newNode;
newNode->prev = dllTemp;
dllTemp = newNode;
sllTemp = sllTemp->next;
}
}
void printList(Node* head)
{
Node* temp = head;
cout << "Forward List: ";
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
int main() {
SinglyLinkedList sll;
sll.insert(1);
sll.insert(2);
sll.insert(3);
DoublyLinkedList dll;
dll.convertFromSingly(sll);
dll.printList(dll.head);
return 0;
}