PHP 逆轉單鏈表

來源:互聯網
上載者:User
 1 <?php 2     #逆轉單鏈表 3     class Node { 4         public $data = null; 5         public $next = null; 6     } 7  8     #遞迴版本 9     #思想是一直遞迴到倒數第二個非空節點,並將其next->next指向自己,將自己的next指向null10     #為了獲得逆轉後的頭結點,在最後一個非空節點,即cnode->next == null時,將節點返回11     function reverse_list_r($node) {12         if ($node->next == null) {13             return $node;14         } else {15             $head = reverse_list_r($node->next);16             $node->next->next = $node;17             $node->next = null;18             return $head;19         }20     }21 22     #非遞迴版本23     #思想是需要儲存下三個節點,分別是cnode,next(cnode->next),next2(cnode->next->next)24     #每次要執行的操作只有將next->next指向cnode,然後依次將這三個節點後移,直到next == null25     function reverse_list($head) {26         $cnode = $head;27         $next = $head->next;28         $head->next = null;29         while ($next != null) {30             $next2 = $next->next;31             $next->next = $cnode; 32             $cnode = $next;33             $next = $next2;34         }35 36         return $cnode;37     }38 39     #遍曆單鏈表40     function traverse($head) {41         $cnode = $head;42         while ($cnode != null) {43             echo $cnode->data . " ";44             $cnode = $cnode->next;45         }46         echo "<br>";47     }48 49     $head = new Node();50     $n1 = new Node();51     $n2 = new Node();52     $n3 = new Node();53     $head->data = 0;54     $n1->data = 1;55     $n2->data = 2;56     $n3->data = 3;57     $head->next = $n1;58     $n1->next = $n2;59     $n2->next = $n3;60     $n3->next = null;61     traverse($head);62 63     $rhead = reverse_list_r($head);64     traverse($rhead);65 66     $rrhead = reverse_list($rhead);67     traverse($rrhead);68 ?>

0 1 2 3 
3 2 1 0 
0 1 2 3

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.