Skip to content

Commit 6c3bfa2

Browse files
committed
PHP实现单链表插入
1 parent c74ed0f commit 6c3bfa2

File tree

2 files changed

+154
-0
lines changed

2 files changed

+154
-0
lines changed

single_linked_list/node.php

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
<?php
2+
namespace SingleLinedList;
3+
/**
4+
* 链表的结点类
5+
*/
6+
class Node
7+
{
8+
/**
9+
* 节点中数据
10+
*
11+
* @var null
12+
*/
13+
private $data = null;
14+
/**
15+
* 后继指针
16+
*
17+
* @var null
18+
*/
19+
private $next = null;
20+
21+
public function __construct($data, $next)
22+
{
23+
$this->data = $data;
24+
$this->next = $next;
25+
}
26+
/**
27+
* 获取节点数据
28+
*
29+
* @return void
30+
*/
31+
public function getData()
32+
{
33+
return $this->$data;
34+
}
35+
36+
/**
37+
* 设置节点数据
38+
*
39+
* @param mixed $data
40+
* @return void
41+
*/
42+
public function setData($data)
43+
{
44+
if (empty($data)) throw new \Exception('数据不能为空');
45+
$this->$data = $data;
46+
}
47+
48+
/**
49+
* 获取后续指针
50+
*
51+
* @return void
52+
*/
53+
public function getNext()
54+
{
55+
return $this->next;
56+
}
57+
58+
/**
59+
* 设置后续指针
60+
*
61+
* @param Node $next
62+
* @return void
63+
*/
64+
public function setNext($next)
65+
{
66+
if (empty($next)) throw new \Exception('下个节点不能为空');
67+
$this->next = $next;
68+
}
69+
}
70+
71+
72+
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
<?php
2+
namespace SingleLinedList;
3+
require Node.php;
4+
/**
5+
* 实现单链表
6+
*/
7+
class SingleLinedList
8+
{
9+
/**
10+
* 哨兵节点 - 头结点
11+
*
12+
* @var [type]
13+
*/
14+
private $head = null;
15+
16+
/**
17+
* 链表长度
18+
*/
19+
private $length;
20+
21+
/**
22+
* 初始化单链表
23+
*
24+
* @param null $head 头结点
25+
*/
26+
public function __construct($head = null)
27+
{
28+
// 空链表中生成头结点
29+
if ($head == null) {
30+
$this->head = new Node();
31+
} else { // 已有结点生成单链表
32+
$this->head = $head;
33+
}
34+
$this->length = 0;
35+
}
36+
37+
/**
38+
* 获取链表长度
39+
*
40+
* @return int
41+
*/
42+
public function getLength()
43+
{
44+
return $this->length;
45+
}
46+
47+
/**
48+
* 插入数据 采用头插法 插入新数据
49+
*
50+
* @param mixed $data
51+
* @return Node
52+
*/
53+
public function insert($data)
54+
{
55+
return $this->insertDataAfter($this->head, $data);
56+
}
57+
58+
/**
59+
* 在某个节点后插入新的节点
60+
*
61+
* @param Node $originNode 要插入节点
62+
* @param mixed $data 数据
63+
* @return Node
64+
*/
65+
public function insertDataAfter(Node $originNode, $data)
66+
{
67+
if (empty($originNode)) {
68+
return false;
69+
}
70+
$newNode = new Node();
71+
$newNode->setData($data);
72+
/*
73+
* 将新的节点的后续指针指向要插入的节点的后续指针, 避免指针丢失
74+
* 若先将 originNode->next = newNode newNode->next = originNode->next
75+
* 等同于 newNode->next = originNode->next = newNode 指向newNode
76+
*/
77+
$newNode->setNext($originNode->getNext());
78+
$originNode->setNext($newNode);
79+
$this->length++;
80+
return $newNode;
81+
}
82+
}

0 commit comments

Comments
 (0)