@@ -9,7 +9,7 @@ class SingleLinedList
9
9
/**
10
10
* 哨兵节点 - 头结点
11
11
*
12
- * @var [type]
12
+ * @var Node
13
13
*/
14
14
private $ head = null ;
15
15
@@ -45,12 +45,12 @@ public function getLength()
45
45
}
46
46
47
47
/**
48
- * 插入数据 采用头插法 插入新数据
48
+ * 采用头插法 生成倒序链表
49
49
*
50
50
* @param mixed $data
51
51
* @return Node
52
52
*/
53
- public function insert ($ data )
53
+ public function headInsert ($ data )
54
54
{
55
55
return $ this ->insertDataAfter ($ this ->head , $ data );
56
56
}
@@ -79,4 +79,97 @@ public function insertDataAfter(Node $originNode, $data)
79
79
$ this ->length ++;
80
80
return $ newNode ;
81
81
}
82
+
83
+ /**
84
+ * 在某个节点前插入新的节点
85
+ *
86
+ * @param Node $originNode
87
+ * @param mixed $data
88
+ * @return void
89
+ */
90
+ public function insertDataBefore (Node $ originNode , $ data )
91
+ {
92
+ if (empty ($ originNode )) {
93
+ return false ;
94
+ }
95
+ $ preNode = $ this ->getPreNode ($ originNode );
96
+ return $ this ->insertDataAfter ($ preNode , $ data );
97
+ }
98
+
99
+ /**
100
+ * 获取某个节点的前置节点
101
+ *
102
+ * @param Node $node
103
+ * @return void
104
+ */
105
+ public function getPreNode (Node $ node )
106
+ {
107
+ if (empty ($ node )) {
108
+ return false ;
109
+ }
110
+ $ curNode = $ this ->head ;
111
+ $ preNode = $ this ->head ;
112
+
113
+ while ($ curNode !== $ node && $ curNode != null ) {
114
+ $ preNode = $ curNode ;
115
+ $ curNode = $ curNode ->next ;
116
+ }
117
+ return $ preNode ;
118
+ }
119
+
120
+ /**
121
+ * 在某个节点后插入新的节点
122
+ *
123
+ * @param Node $originNode
124
+ * @param Node $newNode
125
+ * @return void
126
+ */
127
+ public function insertNodeAfter (Node $ originNode , Node $ newNode )
128
+ {
129
+ if (empty ($ originNode )) {
130
+ return false ;
131
+ }
132
+ $ newNode ->setNext ($ originNode ->getNext ());
133
+ $ originNode ->setNext ($ newNode );
134
+ $ this ->length ++;
135
+ return true ;
136
+ }
137
+
138
+ /**
139
+ * 打印链表
140
+ *
141
+ * @return void
142
+ */
143
+ public function printList ()
144
+ {
145
+ if (null === $ this ->head ->getNext ()) {
146
+ return false ;
147
+ }
148
+ $ curNode = $ this ->head ;
149
+ $ len = $ this ->length ;
150
+ while ($ curNode ->getNext () !== null && $ len --) {
151
+ echo $ curNode ->getNext ()->getData () . '-> ' ;
152
+ $ curNode = $ curNode ->getNext ();
153
+ }
154
+ echo 'NULL ' . PHP_EOL ;
155
+ return true ;
156
+ }
157
+
158
+ /**
159
+ * 删除结点
160
+ *
161
+ * @param Node $node
162
+ * @return void
163
+ */
164
+ public function delete (Node $ node )
165
+ {
166
+ if (empty ($ node )) {
167
+ return false ;
168
+ }
169
+ $ preNode = $ this ->getPreNode ($ node );
170
+ $ preNode ->setNext ($ node ->getNext ());
171
+ unset($ node );
172
+ $ this ->length --;
173
+ return true ;
174
+ }
82
175
}
0 commit comments