Inserting at the last node

Since we are now tracking the last node, it will be easier to insert a new node at the end. First, we need to check that the list is not empty. If it is empty, then the new node becomes both the first and last node. However, if the list already has a last node, then we have to do the following:

  1. Create the new node.
  2. Make the new node the last node.
  3. Assign the previous last node as the previous link of the current last node.
  4. Assign the previous last node's next link to the new last node's previous link.

Here is the code for that:

    public function insertAtLast(string $data = NULL) { 
$newNode = new ListNode($data);
if ($this->_firstNode === NULL) {
$this->_firstNode = &$newNode;
$this->_lastNode = $newNode;
} else {
$currentNode = $this->_lastNode;
$currentNode->next = $newNode;
$newNode->prev = $currentNode;
$this->_lastNode = $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