DSA Lab#4
DSA Lab#4
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) {}
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_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);
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;
}
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;
}