DEV Community

Wahid
Wahid

Posted on

2

Introduction to Linked Lists in PHP: A Beginner's Guide

Linked Lists are a fundamental data structure in computer science, where elements (called nodes) are connected sequentially through pointers. Unlike arrays, Linked Lists are dynamic, meaning they can grow or shrink in size without the need for resizing operations. In this tutorial, we'll cover the basics of implementing a Linked List in PHP.

Structure of a Linked List Node
Each node in a Linked List consists of two parts:

  1. Data: The value stored in the node.
  2. Next: A reference (pointer) to the next node.

Here’s an example implementation of a basic node in PHP:

class Node {
    public $data;
    public $next;

    public function __construct($data) {
        $this->data = $data;
        $this->next = null;
    }
}
Enter fullscreen mode Exit fullscreen mode

Implementing a Simple Linked List
To manage the nodes, we create a LinkedList class that maintains the head of the list and provides methods to manipulate it.

Basic Operations
1. Add Node to the End
We add a node to the end of the list by iterating through the nodes until we reach the last one.

class LinkedList {
    private $head;

    public function __construct() {
        $this->head = null;
    }

    public function append($data) {
        $newNode = new Node($data);
        if ($this->head === null) {
            $this->head = $newNode;
        } else {
            $current = $this->head;
            while ($current->next !== null) {
                $current = $current->next;
            }
            $current->next = $newNode;
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

2. Display the List
We can traverse the list to print all the elements.

public function display() {
    $current = $this->head;
    while ($current !== null) {
        echo $current->data . " -> ";
        $current = $current->next;
    }
    echo "NULL\n";
}

Enter fullscreen mode Exit fullscreen mode

3. Delete a Node
Deleting a node involves finding the node and updating the pointer of the previous node.

public function delete($data) {
    if ($this->head === null) {
        return;
    }

    if ($this->head->data === $data) {
        $this->head = $this->head->next;
        return;
    }

    $current = $this->head;
    while ($current->next !== null && $current->next->data !== $data) {
        $current = $current->next;
    }

    if ($current->next !== null) {
        $current->next = $current->next->next;
    }
}

Enter fullscreen mode Exit fullscreen mode

Example Usage
Here’s how to use the Linked List implementation:

$linkedList = new LinkedList();
$linkedList->append(10);
$linkedList->append(20);
$linkedList->append(30);

echo "Initial List:\n";
$linkedList->display();

$linkedList->delete(20);
echo "After Deleting 20:\n";
$linkedList->display();

Enter fullscreen mode Exit fullscreen mode

*Output:
*

Initial List:
10 -> 20 -> 30 -> NULL
After Deleting 20:
10 -> 30 -> NULL

Enter fullscreen mode Exit fullscreen mode

Conclusion
Linked Lists are a powerful tool for dynamic data manipulation. While PHP has built-in array functions that often serve similar purposes, understanding Linked Lists is essential for grasping fundamental data structures and improving algorithmic thinking. This implementation provides a starting point for more advanced structures like Doubly Linked Lists and Circular Linked Lists.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (3)

Collapse
 
xwero profile image
david duymelinck • Edited

Nice post!

There is a Doubly linked list available in PHP, php.net/manual/en/class.spldoublyl.... So you only need to create an extended class if you want custom functionality, like the delete method in the post.

Collapse
 
abdulwahidkahar profile image
Wahid

Thank you for the comment, David! I’ll give SPLDoublyLinkedList a try and see how it works. 🔥🙌

Collapse
 
attendancekeeper13 profile image
roughandtough03@gmail.com

Outstanding!

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay