All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0201_0300.s0234_palindrome_linked_list.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0201_0300.s0234_palindrome_linked_list;

// #Easy #Top_100_Liked_Questions #Top_Interview_Questions #Two_Pointers #Stack #Linked_List
// #Recursion #Level_2_Day_3_Linked_List #Udemy_Linked_List #Big_O_Time_O(n)_Space_O(1)
// #2022_07_04_Time_6_ms_(76.07%)_Space_97.6_MB_(56.14%)

import com_github_leetcode.ListNode;

/*
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
/**
 * 234 - Palindrome Linked List\.
 *
 * Easy
 *
 * Given the `head` of a singly linked list, return `true` if it is a palindrome.
 *
 * **Example 1:**
 *
 * ![](https://assets.leetcode.com/uploads/2021/03/03/pal1linked-list.jpg)
 *
 * **Input:** head = [1,2,2,1]
 *
 * **Output:** true 
 *
 * **Example 2:**
 *
 * ![](https://assets.leetcode.com/uploads/2021/03/03/pal2linked-list.jpg)
 *
 * **Input:** head = [1,2]
 *
 * **Output:** false 
 *
 * **Constraints:**
 *
 * *   The number of nodes in the list is in the range [1, 105].
 * *   `0 <= Node.val <= 9`
 *
 * **Follow up:** Could you do it in `O(n)` time and `O(1)` space?
**/
public class Solution {
    public boolean isPalindrome(ListNode head) {
        int len = 0;
        ListNode right = head;
        // Culculate the length
        while (right != null) {
            right = right.next;
            len++;
        }
        // Reverse the right half of the list
        len = len / 2;
        right = head;
        for (int i = 0; i < len; i++) {
            right = right.next;
        }
        ListNode prev = null;
        while (right != null) {
            ListNode next = right.next;
            right.next = prev;
            prev = right;
            right = next;
        }
        // Compare left half and right half
        for (int i = 0; i < len; i++) {
            if (prev != null && head.val == prev.val) {
                head = head.next;
                prev = prev.next;
            } else {
                return false;
            }
        }
        return true;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy