PHP Implementation of [PHP] Data Structure-Link List Creation-Insert-Delete-Find

Keywords: PHP

Link list acquisition elements
1. Declare that node p points to the first node in the list, and j initialization 1 begins
2.j < i, P points to the next node, because P is next to p, so it does not need to be equal to
3. If at the end, p is null, it is not found.


Insertion element
1. Inserting elements is similar to finding, after locating
2. Generate new nodes s, s - > next = P - > next p - > next = s;

Delete elements
1. Delete elements and locate them
2. To bypass, q = P - > next p - > next = q - > next;

 

<?php
class Node{
        public $data;
        public $next;
}
//Create a linked list
$linkList=new Node();
$linkList->next=null;
$temp=$linkList;
for($i=1;$i<=10;$i++){
        $node=new Node();
        $node->data="aaa{$i}";
        $node->next=null;
        $temp->next=$node;
        $temp=$node;
}


//Get elements
function getEle($linkList,$i,&$e){
        $p=$linkList->next;
        //Finding Node Standard Statements
        $j=1;
        while($p && $j<$i){
                $p=$p->next;
                ++$j;
        }   
        if(!$p || $j>$i){
                return false;
        }   
        $e=$p->data;
        return true;
}

//Insertion element
function listInsert(&$linkList,$i,$e){
        $p=$linkList;
        $j=1;
        while($p && $j<$i){
                $p=$p->next;
                ++$j;
        }   
        if(!$p || $j>$i){
                return false;
        }   
        $s=new Node();
        $s->data=$e;
        //Insert element standard statement
        $s->next=$p->next;
        $p->next=$s;
        return true;
}
//Delete elements
function listDelete(&$linkList,$i,&$e){
        $p=$linkList;
        $j=1;
        //Note that the judgment here is that $p - > next is true, mainly after pointing $p - > next to $p - > next - > next.
        while($p->next && $j<$i){
                $p=$p->next;
                ++$j;
        }
        if(!$p->next || $j>$i){
                return false;
        }
        $q=$p->next;//This is the current element.
        $e=$q->data;
        $p->next=$q->next;
        return true;
}
$e="";
//Get elements
getEle($linkList,5,$e);
var_dump($e);
//Insertion element
listInsert($linkList,5,"taoshihan");
//Delete elements
listDelete($linkList,1,$e);
var_dump($e);
var_dump($linkList);

Posted by gmcalp on Mon, 04 Feb 2019 03:54:16 -0800