-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathreverse_linked_list.php
More file actions
77 lines (66 loc) · 1.63 KB
/
reverse_linked_list.php
File metadata and controls
77 lines (66 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
/**
* 反转单链表
* Author:学院君
*/
/**
* 单链表结点类
* Class LinkedListNode
*/
class LinkedListNode
{
/**
* 结点值
*/
public $data;
/**
* 下一个结点指针
* @var LinkedListNode
*/
public $next = null;
}
/**
* 反转单链表并返回头结点实现函数
* @param LinkedListNode $first
* @return LinkedListNode
* @throws Exception
*/
function reverseLinkedList(LinkedListNode $first): LinkedListNode
{
if ($first == null || $first->data == null) {
throw new Exception("输入的链表为空");
}
$reverseHead = null; // 反转后的头结点
$node = $first; // 从头结点开始遍历
$prev = null; // 头结点的前驱结点为空
while ($node != null) {
$next = $node->next;
if ($next == null) {
$reverseHead = $node; // 尾结点转化为头结点
}
$node->next = $prev; // 反转实现,当前结点的前驱结点变成后驱结点
$prev = $node; // 设置下一个结点的前驱结点
$node = $next; // 初始化下一个结点
}
return $reverseHead; // 返回反转后的头结点
}
// 测试代码
$head = new LinkedListNode();
$first = new LinkedListNode();
$first->data = 1;
$head->next = $first;
$second = new LinkedListNode();
$second->data = 2;
$first->next = $second;
$third = new LinkedListNode();
$third->data = 3;
$second->next = $third;
$head->next = $first;
try {
$first = reverseLinkedList($head->next);
} catch (Exception $exception) {
echo $exception->getMessage();
return;
}
$head->next = $first;
var_dump($first->data); // 3