php链表反转
时间: 2023-06-28 21:03:56 浏览: 148
python 实现 反转链表
以下是 PHP 实现链表反转的示例代码:
```php
class ListNode {
public $val = 0;
public $next = null;
function __construct($val) {
$this->val = $val;
}
}
function reverseList($head) {
$prev = null;
$curr = $head;
while ($curr != null) {
$next = $curr->next;
$curr->next = $prev;
$prev = $curr;
$curr = $next;
}
return $prev;
}
// 测试代码
$a = new ListNode(1);
$b = new ListNode(2);
$c = new ListNode(3);
$d = new ListNode(4);
$a->next = $b;
$b->next = $c;
$c->next = $d;
echo "原链表:";
$current = $a;
while ($current != null) {
echo $current->val . " -> ";
$current = $current->next;
}
echo "null\n";
$reversed = reverseList($a);
echo "反转链表:";
$current = $reversed;
while ($current != null) {
echo $current->val . " -> ";
$current = $current->next;
}
echo "null\n";
```
输出结果为:
```
原链表:1 -> 2 -> 3 -> 4 -> null
反转链表:4 -> 3 -> 2 -> 1 -> null
```
其中,`ListNode` 类表示链表节点,`reverseList` 函数接收一个链表头节点 `$head`,并返回链表反转后的头节点。具体实现中,使用三个指针 `$prev`、`$curr` 和 `$next` 分别表示前一个节点、当前节点和下一个节点,不断遍历链表,将当前节点的 `next` 指针指向前一个节点,然后将三个节点指针向右移动一个位置,直到遍历完整个链表。
阅读全文