234.Palindrome Linked List

Solution 1: O(n) time .However, the reverse operation will destroy the original List

https://leetcode.com/problems/palindrome-linked-list/discuss/64501/

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head){
        ListNode prev = null;
        while(head != null){
            ListNode nextNode = head.next;
            head.next = prev;
            prev = head;
            head = nextNode;
        }
        return prev;
    }
    public boolean isPalindrome(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        // if odd, fast.next = null
        // if even, fast = null;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        if(fast != null){
            slow = slow.next;
        }
        ListNode l2 = reverseList(slow);
        ListNode l1 = head;
        while(l2 != null){
            int val1 = l1.val;
            int val2 = l2.val;
            if( val1 != val2){
                return false;
            }
            l1 = l1.next;
            l2 = l2.next;
        }
        return true;        
    }
}

results matching ""

    No results matching ""