LeetCode 234: Palindrome Linked List
Problem Description
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)
Solutions
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;
}
}
Related LeetCode Problems
Loading editor...