Inserting at first the node

When we add a node at the front or head, we have to check whether the list is empty or not. If the list is empty, both the first and last node will point to the newly created node. However, if the list already has a head, then we have to do the following:

  1. Create the new node.
  2. Make the new node as the first node or head.
  3. Assign the previous head or first node as the next, to follow the newly created first node.
  4. Assign the previous first node's previous link to the new first node.

Here is the code for that:

    public function insertAtFirst(string $data = NULL) {
$newNode = new ListNode($data);
if ($this->_firstNode === NULL) {
$this->_firstNode = &$newNode;
$this->_lastNode = $newNode;
} else {
$currentFirstNode = $this->_firstNode;
$this->_firstNode = &$newNode;
$newNode->next = $currentFirstNode;
$currentFirstNode->prev = $newNode;
}
$this->_totalNode++;
return TRUE;
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset