Data Assignment 1
Data Assignment 1
Question 2
#include <iostream>
using namespace std;
struct Node
{
int data;
Node* next;
Node(int val) : data(val), next(NULL) {}
};
class LinkedList
{
private:
Node* head = NULL;
public:
int main()
{
LinkedList list;
list.insertNodeAtBeginning(1);
list.insertNodeAtEnd(4);
list.insertNodeInMiddle(2, 1);
list.display();
list.deleteNode(2);
list.display();
system("pause");
return 0;
}
Question 3
Doubly linked list:
#include <iostream>
using namespace std;
struct Node
{
int data;
Node* prev;
Node* next;
};
class DoublyLinkedList
{
private:
public:
int main()
{
DoublyLinkedList dll;
dll.insertNodeAtBeginning(1);
dll.insertNodeAtEnd(3);
dll.insertNodeInMiddle(2, 1);
dll.display();
dll.deleteNode(2);
dll.display();
system("pause");
return 0;
}
system("pause");
return 0;
}
Question:4
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};
class LinkedList
{
public:
Node* head;
LinkedList() : head(nullptr) {}
list.mergeSort();
Question:5
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
class CircularLinkedList
{
private:
Node* head;
public:
CircularLinkedList() : head(nullptr) {}
if (head == nullptr)
{
newNode->next = newNode;
head = newNode;
}
else
{
newNode->next = head->next;
head->next = newNode;
head = newNode;
}
}
void shift(int n)
{
if (head == nullptr)
{
return;
}
while (n < 0)
{
n += 1;
head = head->next;
}
while (n > 0)
{
n -= 1;
Node* current = head;
while (current->next != head)
{
current = current->next;
}
head = current;
}
}
void display()
{
if (head == nullptr)
{
cout << "Circular Linked List is empty" << endl;
return;
}
Node* current = head;
do {
cout << current->data << " ";
current = current->next;
} while (current != head);
cout << endl;
}
};
int main()
{
CircularLinkedList list;
list.insert(1);
list.insert(2);
list.insert(3);
list.insert(4);
list.insert(5);
cout << "Circular Linked List before shifting: ";
list.display();
list.shift(2);
cout << "Circular Linked List after shifting: ";
list.display();
system("pause");
return 0;
}