Implementation of Linked List in PHP

Revision en3, by Eyssant, 2020-06-11 16:26:50

A linked list is a linear data structure, in which the elements are stored in the form of a node. Each node contains two sub-elements. A data part that stores the value of the element and next part that stores the link to the next node as shown in the below image:

Linked List Node

The first node also known as HEAD is always used as a reference to traverse the list. The last node points to NULL. Linked list can be visualized as a chain of nodes, where every node points to the next node.

Linked List

Implementation of Singly Linked List

Representation:

In PHP, singly linked list can be represented as a class and a Node as a separate class. The LinkedList class contains a reference of Node class type.

//node structure
class Node {
  public $data;
  public $next;
}

class LinkedList {
  public $head;

  //constructor to create an empty LinkedList
  public function __construct(){
    $this->head = null;
  }
};


Create a Singly Linked List

Let us create a simple singly linked list which contains three data nodes.

Example
<?php
//node structure
class Node {
  public $data;
  public $next;
}

class LinkedList {
  public $head;

  //constructor to create an empty LinkedList
  public function __construct(){
    $this->head = null;
  }    
};

// test the code  
//create an empty LinkedList
$MyList = new LinkedList();

//Add first node.
$first = new Node();
$first->data = 10;
$first->next = null;
//linking with head node
$MyList->head = $first;

//Add second node.
$second = new Node();
$second->data = 20;
$second->next = null;
//linking with first node
$first->next = $second;

//Add third node.
$third = new Node();
$third->data = 30;
$third->next = null;
//linking with second node
$second->next = $third;
?>
Tags #linked list, #data structure, #programming, #data structures

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en13 English Eyssant 2020-06-11 18:41:24 0 (published)
en12 English Eyssant 2020-06-11 18:40:29 215 (saved to drafts)
en11 English Eyssant 2020-06-11 16:58:26 0 (published)
en10 English Eyssant 2020-06-11 16:56:38 20
en9 English Eyssant 2020-06-11 16:55:21 24
en8 English Eyssant 2020-06-11 16:53:45 36
en7 English Eyssant 2020-06-11 16:50:46 116 Tiny change: '\n~~~~~\n</div>\n<br>\n<h' -> '\n~~~~~\n<br>\n<h'
en6 English Eyssant 2020-06-11 16:44:39 21
en5 English Eyssant 2020-06-11 16:43:34 62
en4 English Eyssant 2020-06-11 16:41:49 4914
en3 English Eyssant 2020-06-11 16:26:50 1693
en2 English Eyssant 2020-06-11 16:22:28 86
en1 English Eyssant 2020-06-11 16:21:30 753 Initial revision (saved to drafts)