这是在一个简单的class下面创建Singly Link List
class Node
{
public $data;
public $next;
public function __construct( $data, $next )
{
$this->data = $data;
$this->next = $next;
}
}
我正在使用以下内容添加新节点。。。
$e = new Node( 2, null );
$d = new Node( 15, $e );
$c = new Node( 9, $d );
$b = new Node( 4, $c );
$a = new Node( 3, $b );
当我打印$a时,它显示
Node Object
(
[data] => 3
[next] => Node Object
(
[data] => 4
[next] => Node Object
(
[data] => 9
[next] => Node Object
(
[data] => 15
[next] => Node Object
(
[data] => 2
[next] =>
)
)
)
)
)
这是正确的!那么现在我该如何根据节点的值来删除它呢?比如奇数还是偶数?
if ( $node->data % 2 == 0 ) {}
最终结果应该是…
Node Object
(
[data] => 4
[next] => Node Object
(
[data] => 2
[next] =>
)
)
您可以在Node
类上定义此方法:
public function filter($callback) {
$dummy = new Node(null, null);
$tail = $dummy;
$node = $this;
while ($node != null) {
if ($callback($node->data)) {
$tail = $tail->next = $node;
}
$node = $node->next;
}
$tail->next = null;
return $dummy->next;
}
然后在你的主程序中,你可以这样做:
$z = $a->filter(function ($data) {
return $data % 2 == 0;
});
在您的示例案例中,$z
将表示列表4->2
。