234. Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
We can solve this problem in three steps:
- finds the middle of the linked list
- reverses the second half of the linked list
- traverses from the head and end of the linked list and determines if each of the numbers are equal
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
private ListNode findMiddle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
private ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode oldNext = curr.next;
curr.next = prev;
prev = curr;
curr = oldNext;
}
return prev;
}
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
ListNode middle = findMiddle(head);
ListNode ptr1 = reverseList(middle);
ListNode ptr2 = head;
while (ptr1 != null && ptr2 != null) {
if (ptr1.val != ptr2.val) {
return false;
}
ptr1 = ptr1.next;
ptr2 = ptr2.next;
}
return true;
}
}