LeetCode 234: Palindrome Linked List Solution
Master LeetCode problem 234 (Palindrome Linked List), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
234. Palindrome Linked List
Problem Explanation
Explanation
To check if a linked list is a palindrome, we can follow these steps:
- Find the middle of the linked list using the slow and fast pointer technique.
- Reverse the second half of the linked list.
- Compare the first half with the reversed second half to determine if it is a palindrome.
Time complexity: O(n)
Space complexity: O(1)
Solution Code
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode slow = head;
ListNode fast = head;
// Find the middle of the linked list
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// Reverse the second half of the linked list
ListNode prev = null;
ListNode curr = slow;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
// Compare the first half with the reversed second half
ListNode firstHalf = head;
ListNode secondHalf = prev;
while (secondHalf != null) {
if (firstHalf.val != secondHalf.val) {
return false;
}
firstHalf = firstHalf.next;
secondHalf = secondHalf.next;
}
return true;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 234 (Palindrome Linked List)?
This page provides optimized solutions for LeetCode problem 234 (Palindrome Linked List) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 234 (Palindrome Linked List)?
The time complexity for LeetCode 234 (Palindrome Linked List) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 234 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 234 in Java, C++, or Python.