Reversing a Singly-Linked List in PHP: A Simple Approach

Athira Radhakrishnan
2 min readMar 26, 2024

--

A singly-linked list consists of nodes, each containing a value and a reference (or pointer) to the next node in the sequence. In this post, we’ll explore a PHP solution that efficiently reverses a singly-linked list.

Introduction

Given the head of a singly linked list, reverse the list, and return the reversed list.

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Reversing a singly-linked list involves changing the direction of pointers, effectively flipping the list.

Exploring the Code

Let’s delve into the PHP class Solution and its method reverseList($head):

/**
* Definition for a singly-linked list.
* class ListNode {
* public $val = 0;
* public $next = null;
* function __construct($val = 0, $next = null) {
* $this->val = $val;
* $this->next = $next;
* }
* }
*/
class Solution {

/**
* @param ListNode $head
* @return ListNode
*/
function reverseList($head) {
$temp = null;
while($head != null) {
$temp2 = $head->next;
$head->next = $temp;
$temp = $head;
$head = $temp2;
}
return $temp;
}
}

How it Works

  1. Initialization: The function initializes a variable $temp to hold the reversed list and sets it to null initially.
  2. Reversal Logic:
    - Inside the while loop, it iterates through each node of the original list.
    - For each node, it stores the next node ($temp2) to avoid losing the reference.
    - It then updates the next pointer of the current node to point to the previously reversed list ($temp).
    - Updates the $temp to the current node for the next iteration.
    - Advances to the next node in the original list.
  3. Return Value: Finally, it returns the reversed list ($temp), which now represents the original list in reverse order.

Time and Space Complexity

Time Complexity: O(n) where n is the number of nodes in the linked list.

Space Complexity: O(1) — Constant space is used throughout the process, regardless of the size of the input list.

Conclusion

The provided PHP solution efficiently reverses a singly-linked list using an iterative approach.

Happy Coding :)

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Athira Radhakrishnan
Athira Radhakrishnan

Written by Athira Radhakrishnan

Systems Engineer | PHP | SQL | Magento | Aspiring Cybersecurity Student | Professionally active since 2021 | GitHub : https://github.com/AthiraBR

No responses yet

Write a response