1. 程式人生 > >[LeetCode] 234. Palindrome Linked List

[LeetCode] 234. Palindrome Linked List

題:https://leetcode.com/problems/palindrome-linked-list/description/

題目

Given a singly linked list, determine if it is a palindrome.

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

Follow up:
Could you do it in O(n) time and O(1) space?

題目大意

判斷 連結串列是否為 迴文。

思路

1.用slow ,fast指標 找出連結串列的中間的及結點。

網上有多種方法設定slow、fast與 迴圈的判斷條件。

我這裡用的 是

fast = head
slow = head
while(fast.next != null && fast.next.next !=null)

這樣 fast 指向的 必有結點。
當連結串列為奇數結點時,fast停在倒數第一個結點上。slow 在 中間結點上。
當連結串列為偶數時,fast停在倒數第二個結點上。slow在 前一半的最後一個結點上。

slow.next 便是 後半連結串列的 頭結點。

2.擷取後半連結串列 翻轉。

3.將後翻轉的後半連結串列 與 原連結串列 逐行對比。遍歷中數值不同,返回false。
當後半連結串列的遍歷指標halfHead 或 原連結串列 遍歷指標 head 為null 跳出迴圈。

4.若halfHead、head 均為null,兩連結串列 相同長度,返回 true。
若head!=null、head.next=null,最初連結串列為奇數。原連結串列比後半連結串列多一個結點,返回true。

否則,返回false。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution { public boolean isPalindrome(ListNode head) { if(head == null) return true; ListNode slow = head,fast = head; while(fast.next != null && fast.next.next != null){ fast = fast.next.next; slow = slow.next; } //找到中間結點 ListNode tTailNode; tTailNode = slow; //獲得後半截連結串列的頭結點。 slow = slow.next; //截段後半連結串列 tTailNode.next = null; //翻轉後半連結串列 ListNode halfHead = null; while(slow!=null){ ListNode tNode = slow.next; slow.next =halfHead; halfHead = slow; slow = tNode; } // 兩 連結串列 對比 while(head != null && halfHead!=null){ if(head.val != halfHead.val) return false; head = head.next; halfHead = halfHead.next; } if((head==null && halfHead==null) ||(head != null && head.next == null)) return true; return false; } }