札记之PHP实现合并两个有序链表

合并两个有序链表,思路很简单,类似合并两个数组,两两进行比较,依次找出小的元素放入新链表中;

示例 1:
输入:[1,3,5,7,9] [2,4,6,8,10]
输出:[1,2,3,4,5,6,7,8,9,10]

代码实现

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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
class ListNode
{
private $data;
private $next;
public function __construct(string $data)
{
$this->data = $data;
}
public function __get($var)
{
return $this->$var;
}
public function __set($var, $val)
{
return $this->$var = $val;
}
}

class LinkedList
{
private $head = NULL;
private $length = 0;
private $currentNode;

public function insert(string $data = NULL)
{
$newNode = new ListNode($data);
if ($this->head === NULL) {
$this->head = &$newNode;
} else {
$currentNode = $this->head;
while ($currentNode->next !== NULL) {
$currentNode = $currentNode->next;
}
$currentNode->next = $newNode;
}
$this->length++;
return true;
}

public function getList()
{
return $this->head;
}

public function setList($head)
{
$this->head = $head;
}

public function mergerSortedList($listA, $listB)
{
if ($listA == NULL) {
return $listB;
}
if ($listB == NULL) {
return $listA;
}
$pListA = $listA->head;
$pListB = $listB->head;

$newNode = new ListNode(0);
$currentNode = $newNode;

while ($pListA != NULL && $pListB != NULL) {
if ($pListA->data <= $pListB->data) {
$currentNode->next = $pListA;
$pListA = $pListA->next;
} else {
$currentNode->next = $pListB;
$pListB = $pListB->next;
}
$currentNode = $currentNode->next;
}
//没处理完的放后面
if ($pListA == NULL) {
$currentNode->next = $pListA;
}
if (!$pListB == NULL) {
$currentNode->next = $pListB;
}
return $newNode;
}

public function display()
{
echo 'LinkList length: ' . $this->length . PHP_EOL;
$currentNode = $this->head;
while ($currentNode !== NULL) {
echo $currentNode->data . PHP_EOL;
$currentNode = $currentNode->next;
}
}
}

$listA = new LinkedList();
$listA->insert(1);
$listA->insert(3);
$listA->insert(5);
$listA->insert(7);
$listA->insert(9);

$listB = new LinkedList();
$listB->insert(2);
$listB->insert(4);
$listB->insert(6);
$listB->insert(8);
$listB->insert(10);

$mergeList = new LinkedList();
$list = $mergeList->mergerSortedList($listA, $listB);
$mergeList->setList($list);
$mergeList->display();

运行结果

1
2
3
4
5
6
7
8
9
10
11
0
1
2
3
4
5
6
7
8
9
10
-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!