zoukankan      html  css  js  c++  java
  • PHP模拟链表操作

    PHP模拟链表操作

    一、总结

    1、类成员用的是->

    2、对象节点相连的话因为是对象,所以不用取地址符号

    3、数组传递参数的时候传引用的方法 ,&

    二、PHP模拟链表操作

    代码一:

     1 /**
     2  * Class Node
     3  * PHP模拟链表的基本操作
     4  */
     5 class Node{
     6     public $data = '';
     7     public  $next = null;
     8 }
     9 //初始化
    10 function init($linkList){
    11     $linkList->data = 0; //用来记录链表长度
    12     $linkList->next = null;
    13 }
    14 //头插法创建链表
    15 function createHead(&$linkList,$length){
    16     for($i=0;$i<$length;$i++){
    17         $newNode = new Node();
    18         $newNode->data = $i;
    19         $newNode->next = $linkList->next;//因为PHP中对象本身就是引用所以不用再可用“&”
    20         $linkList->next = $newNode;
    21         $linkList->data++;
    22     }
    23 }
    24 //尾插法创建链表
    25 function createTail(&$linkList,$length){
    26     $r = $linkList;
    27     for($i=0;$i<$length;$i++){
    28         $newNode = new Node();
    29         $newNode->data = $i;
    30         $newNode->next = $r->next;
    31         $r->next = $newNode;
    32         $r = $newNode;
    33         $linkList->data++;
    34     }
    35 }
    36 //在指定位置插入指定元素
    37 function insert($linkList,$pos,$elem){
    38     if($pos<1 && $pos>$linkList->data+1){
    39         echo "插入位置错误!";
    40     }
    41     $p = $linkList;
    42     for($i=1;$i<$pos;$i++){
    43         $p = $p->next;
    44     }
    45     $newNode = new Node();
    46     $newNode->data = $elem;
    47     $newNode->next = $p->next;
    48     $p->next = $newNode;
    49 }
    50 //删除指定位置的元素
    51 function delete($linkList,$pos){
    52     if($pos<1 && $pos>$linkList->data+1){
    53         echo "位置不存在!";
    54     }
    55     $p = $linkList;
    56     for($i=1;$i<$pos;$i++){
    57         $p = $p->next;
    58     }
    59     $q = $p->next;
    60     $p->next = $q->next;
    61     unset($q);
    62     $linkList->data--;
    63 }
    64 //输出链表数据
    65 function show($linkList){
    66     $p = $linkList->next;
    67     while($p!=null){
    68         echo $p->data." ";
    69         $p = $p->next;
    70     }
    71     echo '<br/>';
    72 }
    73 
    74 $linkList = new Node();
    75 init($linkList);//初始化
    76 createTail($linkList,10);//尾插法创建链表
    77 show($linkList);//打印出链表
    78 insert($linkList,3,'a');//插入
    79 show($linkList);
    80 delete($linkList,3);//删除
    81 show($linkList);

    代码2:

  • 相关阅读:
    jQuery.hover() 函数详解
    深入了解css的行高Line Height属性
    yii2 restfulapi QueryParamAuth验证
    yii2 restfulapi 的配置和访问
    yii2 urlmanager的配置
    xubuntu install nodejs
    使用Putty连接VirtualBox的Ubuntu
    mvc与mvvm
    对二叉树进行广度优先遍历
    JavaScript 中的 FileReader
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/9011188.html
Copyright © 2011-2022 走看看