#include <bits/stdc++.h> // Includes all standard C++ libraries
int data; // Value in the node
Node* next; // Pointer to the next node
Node(int data) { // Constructor to initialize a new node
void printList(Node* head) {
cout << "List is Empty!" << endl;
cout << "Singly List : ";
cout << head->data << " "; // Print node value
head = head->next; // Move to next node
void insertAtHead(Node* &head, int data) {
Node *temp = new Node(data); // Create new node
temp->next = head; // Point it to current head
head = temp; // Update head
void insertAtTail(Node* &tail, int data) {
Node *temp = new Node(data); // Create new node
tail->next = temp; // Append after current tail
tail = temp; // Update tail
void insertAtMiddle(Node* &head, Node* &tail, int data, int pos) {
insertAtHead(head, data); // Special case: insert at head
while(temp != NULL && pos > 2) { // Move to (pos-1)th node
if(temp == NULL || pos <= 0) {
cout << "Invalid Position!" << endl;
Node *insertNode = new Node(data);
insertNode->next = temp->next; // Link new node to next node
temp->next = insertNode; // Link previous node to new node
if(insertNode->next == NULL) { // If inserted at end, update tail
void deletePosition(Node* &head, int pos) {
if(pos == 1) { // Special case: delete head
while(temp != NULL && pos > 2) { // Move to (pos-1)th node
if(temp == NULL || temp->next == NULL || pos <= 0) {
cout << "Invalid Position!" << endl;
Node* target = temp->next; // Node to delete
temp->next = target->next; // Skip the target node
void deleteValue(Node* &head, int val) {
if(head->data == val) { // If head contains the value
val = INT_MIN; // Mark as found
if(prev->next == NULL || val != INT_MIN) {
cout << "Value Not Found!" << endl;
prev->next = temp->next; // Remove node
Node* getMiddle(Node* head) {
if(head == NULL || head->next == NULL) {
return head; // 0 or 1 node only
Node* fast = head; // Fast pointer moves 2 steps
Node* slow = head; // Slow pointer moves 1 step
while(fast != NULL && fast->next != NULL) {
return slow; // When fast reaches end, slow is at middle
Node *head = new Node(1); // Create first node
for(int i=1; i<=5; i++) {
insertAtTail(tail, pow(2,i)); // Insert 2, 4, 8, 16, 32
printList(head); // Print the entire list
Node* mid = getMiddle(head); // Get middle node
cout << "Middle Node : " << mid->data << endl;