1.php实现单链表
<span style="color:#000000">class singleLink
{
public $id;
public $name;
public $next;
public function __construct($id=null, $name=null)
{
$this->id = $id;
$this->name = $name;
$this->next = null;
}
//输出单链表
public function showLink($head)
{
$current = $head;
while ($current->next != null) {
echo $current->next->id."-->".$current->next->name."<br>";
$current = $current->next;
}
}
//增加节点
public function addLink($head, $id, $name)
{
$link = new singleLink($id, $name); //实例化新节点
$current = $head; //临时指针指向头节点
while ($current->next != null) { //找出插入节点处
if ($current->next->id > $id) {
break;
}
$current = $current->next;
}
$link->next = $current->next; //插入节点
$current->next = $link;
}
//删除节点
public function delLink($head, $id)
{
$current = $head;
while ($current->next != null) {
if ($current->next->id == $id) {
break;
}
$current = $current->next;
}
$current->next = $current->next->next;
}
//修改节点
public function updateLink($head, $id, $name)
{
$current = $head;
while ($current->next != null) {
if ($current->next->id == $id) {
break;
}
$current = $current->next;
}
$current->next->name = $name;
}
//根据id查找name
public function getName($head, $id)
{
$current = $head;
while ($current->next != null) {
if ($current->next->id == $id) {
break;
}
$current = $current->next;
}
echo $current->next->name."<br>";
}
}
//初始化单链表
$single = new singleLink();
echo "-----------添加节点1-----------<br>";
$single->addLink($single,1,'路飞');
$single->addLink($single,7,'鸣人');
$single->addLink($single,3,'柯南');
$single->addLink($single,6,'孙悟空');
$single->showLink($single);
echo "-----------查找节点3的名称-----------<br>";
$single->getName($single,3);
echo "-----------修改节点7-----------<br>";
$single->updateLink($single,7,"漩涡鸣人");
$single->showLink($single);
echo "--------------删除节点6---------------<br>";
$single->delLink($single,6);
$single->showLink($single);</span>
2.php用环形链表解决约瑟夫问题
2、从某个编号($start)开始报数
3、数到某个数($num)的时候,此人出列,下一个人重新报数
class circleLink
{
private $id;
private $next;
private $head;
public function __construct($id=null, $next=null)
{
$this->id = $id;
$this->next = $next;
}
public function Joseph($sum, $num, $start)
{
$cur = null;
for ($i = 1; $i < $sum+1; $i++) {
$newCircle = new circleLink($i);
if ($i == 1) {
$this->head = $newCircle;
$this->head->next = $newCircle;
$cur = $this->head;
} else {
$cur->next = $newCircle;
$cur->next->next = $this->head;
$cur = $cur->next;
}
}
$pre = $this->head;
while ($pre->next != $this->head) {
$pre = $pre->next;
}
if ($start != null) {
for ($i = 1; $i < $start; $i++) {
$this->head = $this->head->next;
$pre = $pre->next;
}
}
while ($pre != $this->head) {
for ($i = 0; $i < $num-1; $i++) {
$this->head = $this->head->next;
$pre = $pre->next;
}
echo "出队的数为:".$this->head->id."<br>";
$pre->next = $this->head->next;
$this->head = $this->head->next;
}
echo "最后留下的数为:".$this->head->id;
}
}
$circle = new CircleLink();
$circle->Joseph(5,2,1);