1. 构造单链表, 以及反转单链表的算法 方式有两个: 迭代 与 递归 https://blog.csdn.net/william_n/article/details/109038448 code:
<?php
// 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) {
// 可能没有节点或者只剩一个节点[尾节点], 递推结束条件 if ($head == null || $head->next == null) {
return $head; }
$p = $this->reverseList($head->next); $head->next->next = $head; $head->next = null; return $p; } // /** // * 迭代 // * @param ListNode $head // * @return ListNode // */ // function reverseList($head) {
// $pre = null; // $cur = $head; // $temp = null; // while($cur != null) // {
// $temp = $cur->next; // $cur->next = $pre; // $pre = $cur; // $cur = $temp; // } // return $pre; // } }
$node5 = new ListNode(5, null); $node4 = new ListNode(4, $node5); $node3 = new ListNode(3, $node4); $node2 = new ListNode(2, $node3); $node1 = new ListNode(1, $node2);
$linkedList = $node1; // $node1 即 head节点 var_export($node1);
// 开始执行算法 $solution = new Solution(); $reverseLinkedList = $solution->reverseList($node1); var_export($reverseLinkedList);
输出:
单链表结构
ListNode::__set_state(array( 'val' => 1, 'next' => ListNode::__set_state(array( 'val' => 2, 'next' => ListNode::__set_state(array( 'val' => 3, 'next' => ListNode::__set_state(array( 'val' => 4, 'next' => ListNode::__set_state(array( 'val' => 5, 'next' => NULL, )), )), )), )), ))
反转后的单链表
ListNode::__set_state(array( 'val' => 5, 'next' => ListNode::__set_state(array( 'val' => 4, 'next' => ListNode::__set_state(array( 'val' => 3, 'next' => ListNode::__set_state(array( 'val' => 2, 'next' => ListNode::__set_state(array( 'val' => 1, 'next' => NULL, )), )), )), )), ))
扩展: 使用数组构造单链表 见: Note: https://blog.csdn.net/william_n/article/details/103609382 // 数据结构与算法 - PHP -- 其中有详细的使用数组构造单链表 在 PHP 中,数组集成了所有数据结构,如数组、List、散列表、Map等,而且由于 PHP 不支持指针,所以不能实现真正的链表,比如在插入、删除的时候指针指向的变动无法实现,只能笼统通过 array_splice 函数实现元素插入和删除,也就无法区别实现单向链表、双向链表和循环链表。 2. TBD |