1.将单链表中终端结点的指针端由空指针改为指向头结点,单循环链表,循环链表和单链表的主要差异就在于循环的判断条件上
原来是判断p->next是否为空,现在则是p->next不等于头结点,则循环未结束
2.指向终端结点的尾指针代表该循环链表
3.创建循环链表关键是头结点指向自身,最后一个终端结点指向头结点
<?php class Node{ public $data; public $next; } //创建一个链表 $linkList=new Node(); //头结点指向自身 $linkList->next=$linkList; $temp=$linkList; for($i=1;$i<=10;$i++){ $node=new Node(); $node->data="aaa{$i}"; //最后一个结点指向头结点 $node->next=$linkList; $temp->next=$node; $temp=$node; } //循环链表的遍历 function printLoopLink($linkList){ $p=$linkList; //头结点 $head=$linkList; //如果下一个结点是头结点代表结束 while($p->next!=$head){ $p=$p->next; print_r($p->data." "); } } //循环链表的优势 function printLoopLink3($linkList){ //循环链表的优势,从第三个结点开始遍历,遍历全部链表 $p=$linkList->next->next->next; $head=$linkList->next->next->next; while($p->next!=$head){ $p=$p->next; print_r($p->data." "); } } printLoopLink($linkList); printLoopLink3($linkList);