1. 程式人生 > >[Leetcode] 234. 迴文連結串列

[Leetcode] 234. 迴文連結串列

題目描述:

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

示例 1:

輸入: 1->2
輸出: false

示例 2:

輸入: 1->2->2->1
輸出: true

進階:
你能否用 O(n) 時間複雜度和 O(1) 空間複雜度解決此題?

解題思路:

第一步:

第二步:

程式碼實現(Java語言):

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        ListNode slow = head,fast = head;
        while(fast != null){
            slow = slow.next;
            if(fast.next == null){
                break;
            }
            fast = fast.next.next;
        }
        slow = reverseList(slow);
        while(slow != null){
            if(slow.val != head.val){
                return false;
            }
            slow = slow.next;
            head = head.next;
        }
        return true;
    }
    public ListNode reverseList(ListNode head) {
        if(head==null || head.next == null)
            return head;
        ListNode nextNode = head.next;
        ListNode cur = head;
        head.next = null;
        ListNode tempNext = null;
        while(nextNode != null){
            tempNext = nextNode.next;
            nextNode.next = cur;
            cur = nextNode;
            nextNode = tempNext;
        }
        return cur;
    }
}