程式設計17:判斷一個列表是否是迴文結構
阿新 • • 發佈:2018-12-01
<?php header("content-type:text/html;charset=utf-8"); /* *判斷一個列表是否是迴文結構 P48 */ class Node{ public $value; public $next; public function __construct($value) { $this->value = $value; } } function isPalindrome1($head){ if($head == null){ return false; }$stack = new SplStack(); $cur = $head; while ($cur != null){ $stack->push($cur->value); $cur = $cur->next; } while ($head != null){ if($head->value == $stack->pop()){ $head = $head->next; } else{ echo "單鏈表不是迴文結構";return false; } } echo "單鏈表是迴文結構"; return true; } function isPalindrome2($head){ if($head == null || $head->next == null){ echo "單鏈表是迴文結構"; return true; } $right = $head->next; $cur = $head; while ($cur->next != null && $cur->next->next != null){ $right = $right ->next; $cur = $cur->next->next; } $stack = new SplStack(); while ($right != null){ $stack->push($right->value); $right = $right->next; } while (! $stack->isEmpty()){ if($head->value != $stack->pop()){ echo "單鏈表不是迴文結構"; return false; } $head = $head->next; } echo "單鏈表是迴文結構"; return true; } function isPalindrome3($head){ if($head == null || $head->next == null){ echo "單鏈表是迴文結構"; return true; } $n1 = $head; $n2 = $head; while ($n2->next != null && $n2->next->next != null){ $n1 = $n1->next; //中間結點 $n2 = $n2->next->next; //終點結點 } $n3 = $n1->next; //右邊連結串列的開頭 $n1->next = null; //右邊連結串列進行翻轉 $next = null; $pre = null; while ($n3 != null){ $next = $n3->next; $n3->next = $pre; $pre = $n3; $n3 = $next; } while ($head != null && $pre != null){ if($head->value != $pre->value){ echo "單鏈表不是迴文結構"; return false; } $head = $head->next; $pre = $pre->next; } echo "單鏈表是迴文結構"; return true; } echo "單鏈表為:"; echo "</br>"; $head1 = new Node(1); $head1->next = new Node(2); $head1->next->next = new Node(3); $head1->next->next->next = new Node(2); $head1->next->next->next->next = new Node(1); print_r($head1); echo "</br>"; echo "</br>"; echo "方法1判斷是否迴文:"; echo "</br>"; echo isPalindrome1($head1); $head2 = new Node(1); $head2->next = new Node(2); $head2->next->next = new Node(3); $head2->next->next->next = new Node(2); $head2->next->next->next->next = new Node(1); echo "</br>"; echo "</br>"; echo "方法2判斷是否迴文:"; echo "</br>"; echo isPalindrome2($head2); $head3 = new Node(1); $head3->next = new Node(2); $head3->next->next = new Node(3); $head3->next->next->next = new Node(2); $head3->next->next->next->next = new Node(1); echo "</br>"; echo "</br>"; echo "方法3判斷是否迴文:"; echo "</br>"; echo isPalindrome3($head3);
輸出結果: