// Node structure for singly linked list
int data; // Stores value
Node* next; // Pointer to next node
// Constructor initializes data and next pointer
// Function to print the linked list
void printList(Node* head) {
cout << "List is Empty!" << endl;
cout << "Singly List : ";
cout << head->data << " ";
head = head->next; // Move to next node
// Insert a node at the head (start) of the list
void insertAtHead(Node* &head, int data) {
Node *temp = new Node(data); // Create new node
temp->next = head; // New node points to current head
head = temp; // Head now points to new node
// Insert a node at the tail (end) of the list
void insertAtTail(Node* &tail, int data) {
Node *temp = new Node(data); // Create new node
tail->next = temp; // Current tail points to new node
tail = temp; // Tail now points to new node
// Insert a node at a specific position (1-based index)
void insertAtMiddle(Node* &head, Node* &tail, int data, int pos) {
if(pos == 1) { // Insert at head if position is 1
insertAtHead(head, data);
// Traverse to (pos-1)th node
while(temp != NULL && pos > 2) {
// If position is invalid
if(temp == NULL || pos <= 0) {
cout << "Invalid Position!" << endl;
// Insert new node after temp
Node *insertNode = new Node(data);
insertNode->next = temp->next;
// Update tail if inserted at end
if(insertNode->next == NULL) {
// Delete a node at given position
void deletePosition(Node* &head, int pos) {
// Deleting the first node
// Traverse to (pos-1)th node
while(temp != NULL && pos > 2) {
// Check for invalid position
if(temp == NULL || temp->next == NULL || pos <= 0) {
cout << "Invalid Position!" << endl;
// Delete the node at position
Node* target = temp->next;
temp->next = target->next;
// Delete the first occurrence of a node with given value
void deleteValue(Node* &head, int val) {
// If head node has the value
// Traverse to find node with matching value
val = INT_MIN; // Mark as found
if(prev->next == NULL || val != INT_MIN) {
cout << "Value Not Found!" << endl;
// Delete the matching node
Node *head = new Node(1); // Initial head node with value 1
Node *tail = head; // Tail initially same as head
// Insert powers of 2 (2 to 32) at tail
for(int i = 1; i <= 5; i++) {
insertAtTail(tail, pow(2, i)); // Inserts: 2, 4, 8, 16, 32
printList(head); // Output: 1 2 4 8 16 32
// Uncomment to test deleting by position
// deletePosition(head, 6);
deleteValue(head, 32); // Deletes node with value 32
printList(head); // Output: 1 2 4 8 16