Getting the Nth position element

As lists are different from arrays, it is not easier to get elements from their positions directly. In order to get an element in the Nth position, we have to iterate to that position and get the element. Here is the code sample for this method:

    public function getNthNode(int $n = 0) { 
$count = 1;
if ($this->_firstNode !== NULL) {
$currentNode = $this->_firstNode;
while ($currentNode !== NULL) {
if ($count === $n) {
return $currentNode;
}
$count++;
$currentNode = $currentNode->next;
}
}
}

We have now written all the required operations for our LinkedList class. Now, let's run the program with different operations. If we run the following program, we will mostly cover all the operations we have written:

$BookTitles = new LinkedList(); 
$BookTitles->insert("Introduction to Algorithm");
$BookTitles->insert("Introduction to PHP and Data structures");
$BookTitles->insert("Programming Intelligence");
$BookTitles->insertAtFirst("Mediawiki Administrative tutorial guide");
$BookTitles->insertBefore("Introduction to Calculus", "Programming Intelligence");
$BookTitles->insertAfter("Introduction to Calculus", "Programming Intelligence");
$BookTitles->display();
$BookTitles->deleteFirst();
$BookTitles->deleteLast();
$BookTitles->delete("Introduction to PHP and Data structures");
$BookTitles->reverse();
$BookTitles->display();
echo "2nd Item is: ".$BookTitles->getNthNode(2)->data;

The output of the preceding code will look like this:

Total book titles: 6
Mediawiki Administrative tutorial guide
Introduction to Algorithm
Introduction to PHP and Data structures
Introduction to Calculus
Programming Intelligence
Introduction to Calculus
Total book titles: 3
Programming Intelligence
Introduction to Calculus
Introduction to Algorithm
2nd Item is: Introduction to Calculus

Now we have a complete implementation of a linked list using PHP 7. One thing we have understood so far is that unlike the implementation of arrays, we have to do lots of operations manually by writing codes. We also have to remember one thing: This is not the only way we can implement a linked list. Many prefer to track both the first and last nodes of the list for a better insert operation. Now, we will look at the complexity of linked list operations in average and worst-case scenarios.

..................Content has been hidden....................

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