札记之链表实现队列

链表实现队列,重要在于出队,详情如下:

思路

  • 初始化:创建一个指向队列节点的head头指针
  • 入队:创建一个新节点,将它添加到链表尾部,如果链表为空,让头指针指向该节点
  • 出队:头指针指向第一个节点, 让头指针指向该节点的下一个节点, 然后返回该节点的值

图示

札记之链表实现队列

代码实现

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
class ListNode
{
private $data;
private $next;
public function __construct(string $data = NULL)
{
$this->data = $data;
}
public function __get($var)
{
return $this->$var;
}
public function __set($var, $val)
{
return $this->$var = $val;
}
}

class linkedQueue
{
private $head;
private $tail;
private $lenght;

public function __construct()
{
$this->head = new ListNode();
$this->tail = $this->head;
$this->length = 0;
}

public function enqueue($data)
{
$newNode = new ListNode();
$newNode->data = $data;
$this->tail->next = $newNode;
$this->tail = $newNode;
$this->length++;
}

public function dequeue()
{
if ($this->length <= 0) {
return false;
}
$node = $this->head->next;
$this->head->next = $this->head->next->next;
$this->length--;
return $node;
}

public function getLenght()
{
return $this->length;
}

public function display()
{
echo 'LinkList length: ' . $this->length . PHP_EOL;
$currentNode = $this->head;
while ($currentNode !== NULL) {
echo $currentNode->data . PHP_EOL;
$currentNode = $currentNode->next;
}
}
}
$queue = new linkedQueue();
$queue->enqueue(1111);
$queue->enqueue(2222);
$queue->enqueue(3333);
print_r($queue->dequeue()->data);
echo PHP_EOL;
print_r($queue->dequeue()->data);
echo PHP_EOL;
print_r($queue->dequeue()->data);

结果:

1
2
3
1111
2222
3333

`

-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!