234. 迴文連結串列
阿新 • • 發佈:2018-11-10
請判斷一個連結串列是否為迴文連結串列。
示例 1:
輸入: 1->2 輸出: false
示例 2:
輸入: 1->2->2->1 輸出: true
思路:
首先建立兩個指標指向連結串列,然後使其中一個指標指向連結串列中間,這裡可以使用另一個指標快速移動,當另一個指標移動速度是前一根指標的一倍時,就可以使slow指標到一半,而fast指標遍歷完了。使用棧接收前一半的所有資料,因為要判斷是否迴文,所以前一半顛倒和後一半比較,如果相等則說明是迴文連結串列。而棧的後進先出恰好符合了這個特性。程式碼如下:
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */ public class Solution { public bool IsPalindrome(ListNode head) { ListNode fast = head; ListNode slow = head; Stack<int> value = new Stack<int>(); //使連結串列快速遍歷 讓slow到達連結串列一半 while (fast != null && fast.next != null) { value.Push(slow.val); slow = slow.next; fast = fast.next.next; } //如果fast不為空則節點數是為奇數,因為當前slow需要指向連結串列的後半部分所以需要後移 if (fast != null) { slow = slow.next; } while (slow !=null) { int v = value.Pop(); if (v != slow.val) { return false; } slow = slow.next; } return true; } }