234. Palindrome Linked List

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

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

这道题看的答案,第一种解法是构造一个原链表的reversed LinkedList, 然后再一一比较元素是否相等。

/**
 * 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 p = head;
        ListNode prev = new ListNode(head.val);
        while (p.next != null){
            ListNode temp = new ListNode(p.next.val);
            temp.next = prev;
            prev = temp;
            p = p.next;
        }
        while (head != null){
            if (head.val != prev.val){
                return false;
            }
            head = head.next;
            prev = prev.next;
        }
        return true;
    }
}

第二种方法是将LinkedList截成两端,然后将后半段reverse. 再比较前半段和reversed后半段是否一致来确定是不是回文串

/**
 * 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 || head.next == null){
            return true;
        }
        ListNode fast = head;
        ListNode slow = head;
        while (fast.next != null && fast.next.next != null){
            fast = fast.next.next;
            slow = slow.next;    
        }
        ListNode secondHalf = slow.next;
        slow.next = null;
        ListNode p1 = secondHalf;
        ListNode p2 = p1.next;
        while (p1 != null && p2 != null){
            ListNode temp = p2.next;
            p2.next = p1;
            p1 = p2;
            p2 = temp;
        }
        //Crucial step, or linkedlist could be circular
        secondHalf.next = null;
        //do not know the situation when p2 != null
        ListNode p = p1;
        ListNode q = head;
        while (q != null && p != null){
            if (q.val != p.val){
                return false;
            }
            q = q.next;
            p = p.next;
        }
        return true;
    }
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/d2adeac44fe2
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞