Open In App

SplDoublyLinkedList in PHP

A Doubly Linked List is a list that contains links to both next and previous nodes. A Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer, together with next pointer and data which are there in singly linked list. Unlike singly linked lists where traversal is only one way, doubly linked lists allow traversals in both ways.



Following are the important terms to understand the concept of doubly linked list:

You may refer to article on Doubly Linked List ( Introduction ) for understanding the doubly linked list in details.



The SplDoublyLinkedList class is a PHP Library class which provides the main functionalities of a doubly linked list in PHP.

Below are some of the basic functions of the SplDoublyLinkedList class:

Below program illustrate the above functions to create and use a doubly linked list:
Program:




<?php
// Program to implement basic PHP functions
// for doubly linked list
  
// Instantiating an object of class SplDoublyLinkedList
$dlist = new SplDoublyLinkedList();
  
// Inserting elements at the end of the list
$dlist->push('geeks');
$dlist->push('for');
$dlist->push('practice');
  
// Displaying the list
echo "Original List : ";
for ($dlist->rewind(); $dlist->valid(); $dlist->next()) {
    echo $dlist->current()." ";
}
  
// Deleting element from the end of the list
$dlist->pop();
  
// Adding a new element at specific index
// Add 'code' at index 2
$dlist->add(2, "code");
  
// Displaying the updated list
echo "\n\nUpdated List : ";
for ($dlist->rewind(); $dlist->valid(); $dlist->next()) {
    echo $dlist->current()." ";
}
  
// Printing the count of nodes
echo "\n\nCount = " . $dlist->count() . "\n";
  
// Printing the node at top of the list
echo "Top = ". $dlist->top() . "\n";
  
// Printing the node at bottom of the list
echo "Bottom = " . $dlist->bottom() . "\n";
  
?>

Output:

Original List : geeks for practice 

Updated List: geeks for code 

Count = 3
Top = code
Bottom = geeks

Article Tags :