Deleting a middle node from a single linked list when pointer to the previous node is not available

前端 未结 24 1384
陌清茗
陌清茗 2020-11-29 20:42

Is it possible to delete a middle node in the single linked list when the only information available we have is the pointer to the node to be deleted and not the pointer to

24条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 21:16

    It's definitely more a quiz rather than a real problem. However, if we are allowed to make some assumption, it can be solved in O(1) time. To do it, the strictures the list points to must be copyable. The algorithm is as the following:

    We have a list looking like: ... -> Node(i-1) -> Node(i) -> Node(i+1) -> ... and we need to delete Node(i).

    1. Copy data (not pointer, the data itself) from Node(i+1) to Node(i), the list will look like: ... -> Node(i-1) -> Node(i+1) -> Node(i+1) -> ...
    2. Copy the NEXT of second Node(i+1) into a temporary variable.
    3. Now Delete the second Node(i+1), it doesn't require pointer to the previous node.

    Pseudocode:

    void delete_node(Node* pNode)
    {
        pNode->Data = pNode->Next->Data;  // Assume that SData::operator=(SData&) exists.
        Node* pTemp = pNode->Next->Next;
        delete(pNode->Next);
        pNode->Next = pTemp;
    }
    

    Mike.

提交回复
热议问题