php循环链表,用php实现一个循环单链表

class CycleSingleLinkedList {

public $head = null;

public $length = 0;

/**

* CycleSingleLinkedList constructor.

* 初始化链表, 使head->next = head

* @param null $data

*/

public function __construct($data = null)

{

$this->head = new Node($data);

$this->head->next = $this->head;

}

public function getHead()

{

return $this->head;

}

/**

* 插入数据, 把最后一个插入的元素指向head

* @param $data

* @return $this

*/

public function insert($data)

{

$current = $this->head->next;

while ($current->next != $this->head) {

$current = $current->next;

}

$current->next = new Node($data, $this->head);

$this->length ++;

return $this;

}

/**

* 从头部插入数据, 直接把head->next->new node->...

* @param $data

* @return $this

*/

public function headInsert($data)

{

$this->head->next = new Node($data, $this->head->next);

$this->length ++;

return $this;

}

/**

* 更新数据, 不更新指针, 只更新数据, 所以只要找到对应的元素就行了

* @param $index

* @param $data

* @return $this|bool

*/

public function update($index, $data)

{

if ($index > $this->length || $this->length <= 0) {

return false;

}

$index = $index < 0 ? $this->length + $index : $index;

$current = $this->head->next;

$i = 0;

while ($i != $index) {

$current = $current->next;

$i ++;

}

$current->data = $data;

return $this;

}

/**

* 删除元素, 从head开始查找, 不从第一位查找, 这样找到的元素就是要删除的元素前一个, 直接更改指针指向即可

* @param $index

* @return $this|bool

*/

public function delete($index)

{

if ($index > $this->length || $this->length <= 0) {

return false;

}

$index = $index < 0 ? $this->length + $index : $index;

// 查找到要删除的元素的前一位, 把指向该元素的指针指向该元素指向的指针, 故从head开始查找

$current = $this->head;

$i = 0;

while ($i != $index) {

$current = $current->next;

$i ++;

}

$current->next = $current->next->next;

$this->length --;

return $this;

}

public function print()

{

echo '


';

$current = $this->head->next;

$i = 0;

while ($current != $this->head) {

echo sprintf('当前第%d个元素: ', $i);

print_r($current->data);

echo '
';

$i ++;

$current = $current->next;

}

}

/**

* 清空链表, head->next->head

*/

public function clear()

{

$this->head->next = $this->head;

}

/**

* 链表反转, head->1->2->3 变成 head->3->2->1

* @return $this

*/

public function reverse()

{

$current = $this->head->next;

$pre = $this->head;

while ($current != $this->head)

{

$next = $current->next;

$current->next = $pre;

$pre = $current;

$current = $next;

}

$this->head->next = $pre;

return $this;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值