Data Structures And Algorithms
Lab # 4
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int iData) : data(iData), next(NULL) {}
};
class Linked_List {
private:
Node* head;
public:
Linked_List() : head(NULL) {}
void add_node_at_head(int iData) {
Node* tmp = new Node(iData);
tmp->next = head;
head = tmp;
}
void add_node_at_tail(int iData) {
if (head == NULL) {
head = new Node(iData);
}
else {
Node* tmp = head;
while (tmp->next != NULL) {
tmp = tmp->next;
}
tmp->next = new Node(iData);
}
}
void add_node_at_position(int iData, int position) {
if (position == 1) {
add_node_at_head(iData);
return;
}
Node* current = head;
int count = 1;
while (current != NULL && count < position - 1) {
current = current->next;
count++;
}
if (current == NULL) {
cout << "Position out of range!" << endl;
return;
}
Node* tmp = new Node(iData);
tmp->next = current->next;
current->next = tmp;
}
bool search_node(int iData) {
Node* tmp = head;
while (tmp != NULL) {
if (tmp->data == iData) {
return true;
}
tmp = tmp->next;
}
return false;
}
void print_all_nodes() {
Node* tmp = head;
while (tmp != NULL) {
cout << tmp->data << " ";
tmp = tmp->next;
}
cout << endl;
}
int count_nodes() {
int count = 0;
Node* tmp = head;
while (tmp != NULL) {
count++;
tmp = tmp->next;
}
return count;
}
void delete_node_at_head() {
if (head != NULL) {
Node* tmp = head;
head = head->next;
delete tmp;
}
}
void delete_node_at_tail() {
if (head == NULL) return;
if (head->next == NULL) {
delete head;
head = NULL;
return;
}
Node* tmp = head;
while (tmp->next->next != NULL) {
tmp = tmp->next;
}
delete tmp->next;
tmp->next = NULL;
}
void delete_node_at_position(int position) {
if (position == 1) {
delete_node_at_head();
return;
}
Node* current = head;
int count = 1;
while (current != NULL && count < position - 1) {
current = current->next;
count++;
}
if (current == NULL || current->next == NULL) {
cout << "Position out of range!" << endl;
return;
}
Node* tmp = current->next;
current->next = current->next->next;
delete tmp;
}
void delete_all_nodes() {
while (head != NULL) {
Node* tmp = head;
head = head->next;
delete tmp;
}
}
~Linked_List() {
delete_all_nodes();
}
};
int main() {
Linked_List list;
list.add_node_at_head(3);
list.add_node_at_tail(7);
list.add_node_at_position(5, 2);
list.add_node_at_tail(9);
cout << "List after insertion: ";
list.print_all_nodes();
int searchValue = 5;
if (list.search_node(searchValue)) {
cout << "Node with data " << searchValue << " found in the list." <<
endl;
}
else {
cout << "Node with data " << searchValue << " not found in the list." <<
endl;
}
cout << "Number of nodes: " << list.count_nodes() << endl;
list.delete_node_at_head();
list.delete_node_at_tail();
list.delete_node_at_position(2);
cout << "List after deletion: ";
list.print_all_nodes();
list.delete_all_nodes();
cout << "List after deleting all nodes: ";
list.print_all_nodes();
return 0;
}