<?php
/**
* 反转一个单向链表
* 算法思路:通过循环遍历链表,重置next索引的指向,让其指向的位置颠倒
* @author nswe
*/
/**
* 单向链表数据结构
*/
class LinkNode
{
//值域
public $value;
//下个节点的指针
public $next;
/**
* 构造函数
* @param $value 节点值
*/
public function __construct($value)
{
$this->value =$value;
}
}
/**
* 反转链表方法
* @param LinkNode $list 链表
*/
function reverseList($list)
{
$current= $list;
$next = $current->next;
//链表的首节点要变成结尾节点,所以next要置空
$current->next = null;
while($next)
{
//保存原来链表的下个节点
$result= $next;
//保存原来链表的下个节点的下个节点到下次循环中
$next= $next->next;
//更改原来链表的下个节点的next索引
$result->next =$current;
//保存下个节点到下次循环中
$current= $result;
}
return $result;
}
/*调用执行代码*/
//动态生成正序列表9个
$result= $firstNode = new LinkNode(1);
$i = 2;
while($i< 10)
{
$firstNode->next =new LinkNode($i);
$firstNode= $firstNode->next;
$i++;
}
/*打印调试结果*/
echo '正序:<br />';
print_r($result);
echo '<br /><br />';
$result= reverseList($result);
echo '逆序:<br />';
print_r($result);