-
Notifications
You must be signed in to change notification settings - Fork 143
/
CircularLinkedList.php
56 lines (44 loc) · 1.17 KB
/
CircularLinkedList.php
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
<?php
namespace DataStructure\CircularLinkedList;
use DataStructure\LinkedList\ListNode;
class CircularLinkedList
{
private $head = null;
private $length = 0;
public function insertAtEnd(string $data = null)
{
$newNode = new ListNode($data);
if ($this->head) {
$currentNode = $this->head;
while ($currentNode->next !== $this->head) {
$currentNode = $currentNode->next;
}
$currentNode->next = $newNode;
} else {
$this->head = &$newNode;
}
$this->length++;
$newNode->next = $this->head;
return true;
}
/**
* 返回特定位置的节点
* @param int $n
* @return null
* complexity O(n)
*/
public function getNthNode(int $n = 0)
{
$count = 0;
if ($this->head !== null && $n <= $this->length) {
$currentNode = $this->head;
while ($currentNode !== null) {
if ($count === $n) {
return $currentNode;
}
$count++;
$currentNode = $currentNode->next;
}
}
}
}