Palindrome Linked List

Given a singly linked list, determine if it is a palindrome.

Follow up:

Could you do it in O(n) time and O(1) space?

Solution:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. public class Solution {
  10. public boolean isPalindrome(ListNode head) {
  11. if (head == null || head.next == null)
  12. return true;
  13. // step 1. cut the original list to two halves
  14. ListNode prev = null, slow = head, fast = head, l1 = head;
  15. while (fast != null && fast.next != null) {
  16. prev = slow;
  17. slow = slow.next;
  18. fast = fast.next.next;
  19. }
  20. prev.next = null;
  21. // step 2. reverse the 2nd half
  22. ListNode l2 = (fast == null) ? reverse(slow) : reverse(slow.next);
  23. // step 3. compare the new two halves
  24. while (l1 != null && l2 != null) {
  25. if (l1.val != l2.val)
  26. return false;
  27. l1 = l1.next;
  28. l2 = l2.next;
  29. }
  30. return true;
  31. }
  32. // helper function: reverse a list
  33. ListNode reverse(ListNode head) {
  34. ListNode prev = null, curr = head, next = null;
  35. while (curr != null) {
  36. next = curr.next;
  37. curr.next = prev;
  38. prev = curr;
  39. curr = next;
  40. }
  41. return prev;
  42. }
  43. }