Recently in the PHP language to achieve a variety of data structure algorithm sequencing, can be said to be a very painful thing, recently encountered a problem, do not know what the reason, put it here, hope to see the people to help
First I wrote such a class in PHP.
Class Listnode{private $val;p rivate $next =null;function __construct ($val) {$this->val= $val;} Public Function __get ($propertyName) {return $this, $propertyName;} Public Function __set ($name, $value) {$this, $name = $value;}}
Then there is an algorithm
1 functionPartitionlinkedlist ($head,$x){2 Var_dump($head);3 $dummy=NewListNode (0);4 $pivot=NewListNode ($x);5 $first=$dummy;6 $second=$pivot;7 $curr=$head-Next;8 9 while($curr!=NULL) {Ten //Var_dump ($curr); One $next=$curr-Next; A Echo $curr-Val; - if($curr->val<$x){ - $first-Next=Clone $curr; the $first=$curr; - $first-Next=NULL; -}Else{ - $second-Next=Clone $curr; + $second=$curr; - $new 2=NewListNode (100); + //$second->next=null; A $second-Next=$new 2; at } - Echo"Dummy"; - Var_dump($dummy); - Echo"Pivot"; - Var_dump($pivot); - $curr=$next; in } - $first-Next=$pivot-Next; to return $dummy; + } - the $arr=Array(4,3,2,1,2,5); * $L=NewListNode (0); $ $L 1=$L;Panax Notoginseng foreach($arr as $nodeval) { - //echo $nodeval. " "; the $new=NewListNode ($nodeval); + //echo $new->val. "; A $L 1-Next=$new; the $L 1=$new; + //Echo $L 1->val; - //echo "<br/>"; $}
The problem is in lines 16th and 21st, and the following is the execution
, when I set next in the list to NULL, the first loop does not turn subsequent next to null, but after the second loop the subsequent next becomes null, and I do not understand why, so I send it here to help you, detailed code can be downloaded to my github (https ://github.com/xzjs/interview_php/blob/master/t31.php)
The confusion of PHP execution