topic
Enter a linked list and print the value of each node of the linked list from the end to the beginning.
Question explanation
One is to use the stack.
The second type is recursion.
Code
//Recursive versionfunction printListFromTailToHead($head) { if($head == NULL){ return []; } $arr = array(); $cur = $head; if($cur->next != null){ $arr = printListFromTailToHead($cur->next); } array_push($arr, $cur->val); return $arr; } //Non-recursive versionfunction printListFromTailToHead($head) { if($head == NULL){ return []; } $cur = $head; $arr = array(); $re = array(); while($cur != NULL){ array_push($arr, $cur->val); $cur = $cur ->next; } while(!empty($arr)){ $tmp = array_pop($arr); array_push($re, $tmp); } return $re; }