Swap Data and Delete Next Node

This approach involves swapping the data of the node that has to be deleted with the data of the next node, after which the next node is deleted.

  • Swap Data: Swap the data of the node to be deleted with the data of the next node.
  • Delete Next Node: Delete the next node

Example: To demonstrate deleting a node without a head pointer using JavaScript.

JavaScript
function deleteNodeSwapData(node) {
    if (node === null || node.next === null) {
        return false;
        // Cannot delete the last node or null node
    }

    let temp = node.data;
    node.data = node.next.data;
    node.next.data = temp;

    node.next = node.next.next;
    // Delete the next node
    return true;
}


// Node definition for the linked list
class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

// Function to print the linked list
function printLinkedList(head) {
    let current = head;
    while (current !== null) {
        console.log(current.data);
        current = current.next;
    }
}

// Create a sample linked list
const head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);

console.log("Original Linked List:");
printLinkedList(head);

// Deleting the node with data 2 
// (assuming we have reference to this node)
const nodeToDelete = head.next;
deleteNodeSwapData(nodeToDelete);

console.log("\nAfter Deleting Node with Data 2:");
printLinkedList(head);

Output
Original Linked List:
1
2
3
4

After Deleting Node with Data 2:
1
3
4

Time Complexity: O(1)

Space Complexity: O(1)

Delete Without Head Pointer using JavaScript

The objective is to remove a node in a JavaScript singly linked list without having a direct reference to the head node. This entails making changes to the node that will be removed without actually using the head pointer.

Below are the approaches to deleting a node without a head pointer using JavaScript:

Table of Content

  • Copy Data and Adjust Pointers
  • Swap Data and Delete Next Node
  • Traverse Entire List

Similar Reads

Copy Data and Adjust Pointers

This approach involves moving the data from the next node to the node that is to be deleted, changing pointers to skip the next node, and then deleting the next node....

Swap Data and Delete Next Node

This approach involves swapping the data of the node that has to be deleted with the data of the next node, after which the next node is deleted....

Traverse Entire List

Another approach, however inefficient, is to search through the whole list until you locate the node that has to be removed before any others. Once located, modify the pointers to eliminate the required node....