java 234. Palindrome Linked List(#)。java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 234. Palindrome Linked List(#)。java相关的知识,希望对你有一定的参考价值。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) return true;
        ListNode prev = null;
        ListNode next = null;
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null )
        {
            // fast and slow pointers need to move before reverse the first half of the list. Otherwise, as the list is reversed, pointer of the next node has changed, which will affect the iteration of the fast and slow pointers.
            fast = fast.next.next; 
            slow = slow.next;
            
            next = head.next;
            head.next = prev;
            prev = head;
            head = next;
            
            
        }
        if(fast != null ) // odd
            slow = slow.next;
        while(prev != null)
        {
            if (slow.val != prev.val) return false;
            // if the problem cares about the original list, we can reverse the first half back as we compare.
            slow = slow.next;
            prev = prev.next;
        }
        return true;
    }
}
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    private ListNode reverse(ListNode head) {
        ListNode newHead = null;
        while (head != null) {
            ListNode next = head.next;
            head.next = newHead;
            newHead = head;
            head = next;
        }
        return newHead;
    }
    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) return true;
        ListNode fast = head, slow = head;
        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        fast = head;
        slow = slow.next;
        ListNode newHead = reverse(slow);
        while (newHead != null) {
            if (newHead.val != fast.val) return false;
            newHead = newHead.next;
            fast = fast.next;
        }
        return true;
    }
}

以上是关于java 234. Palindrome Linked List(#)。java的主要内容,如果未能解决你的问题,请参考以下文章

java 234. Palindrome Linked List(#)。java

java 234. Palindrome Linked List(#)。java

java 234. Palindrome Linked List(#)。java

Java [Leetcode 234]Palindrome Linked List

234. Palindrome Linked List

234. Palindrome Linked List