PHP实现单链表

来源:互联网 发布:风暴英雄有mac版吗 编辑:程序博客网 时间:2024/05/21 09:34
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);
0 0
原创粉丝点击