首页 > 编程 > PHP > 正文

PHP实现单链表

2019-11-08 01:47:32
字体:
来源:转载
供稿:网友
class Node { public $data = ''; public $next = null; public function __construct($data = ''){ $this->data = $data; }}//添加节点function addNode($head,$data){ $cur = $head; while($cur->next != null){ $cur = $cur->next; } $new = new Node($data); $cur->next = $new;}//获取链表长度,元素个数function getLength($head){ $cur = $head; $i = 0; while($cur->next != null){ ++$i; $cur = $cur->next; } return $i;}//遍历元素值function showNode($head){ $cur = $head; while($cur->next != null){ $cur = $cur->next; echo $cur->data.php_EOL; }}//删除节点function delNode($head,$seq){ $cur = $head; $flag = 0; for($i=0;$i<$seq-1;$i++){ $cur = $cur->next; if($cur->next == null){ $flag = 1; break; } } if($flag == 0){ $cur->next = $cur->next->next; }}//插入节点function insertNode($head,$data,$seq){ $cur = $head; $flag = 0; $node = new Node($data); for($i=0;$i<$seq;$i++){ $cur = $cur->next; if($cur->next == null){ $flag = 1; break; } } if($flag == 0){ $node->next = $cur->next; $cur->next = $node; }}//翻转链表function reverseNode($head){ if($head == null){ return $head; } $PRe = $head; $cur = $head->next; $next = null; while($cur != null){ $next = $cur->next; $cur->next = $pre; $pre = $cur; $cur = $next; } $head->next = null; $head = $pre; return $head;} $head = new Node('head');addNode($head,1);addNode($head,2);addNode($head,3);print_r($head);showNode($head);insertNode($head,0,2);print_r($head);delNode($head,3);print_r($head);$len = getLength($head);print_r($len);$head = reverseNode($head);print_r($head);
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表