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?

分析

首先要寻找中点,原理是使用快慢指针,每次快指针走两步,慢指针走一步。同时还要用栈,每次慢指针走一步,都把值存入栈中。等快指针走完时,链表的前半段都存入栈中了。最后慢指针继续往前走,每次与栈顶元素进行比较。空间复杂度O(n)

如何做到用O(1)空间呢?可以先找到中点,把后半段reverse一下,然后比较两个小链表。

代码

  1. // Palindrome Linked List
  2. // Time Complexity: O(n), Space Complexity: O(1)
  3. public class Solution {
  4. public boolean isPalindrome(ListNode head) {
  5. if (head == null) return true;
  6. final ListNode middle = findMiddle(head);
  7. middle.next = reverse(middle.next);
  8. ListNode p1 = head;
  9. ListNode p2 = middle.next;
  10. while (p1 != null && p2 != null && p1.val == p2.val) {
  11. p1 = p1.next;
  12. p2 = p2.next;
  13. }
  14. return p2 == null;
  15. }
  16. private static ListNode findMiddle(ListNode head) {
  17. if (head == null) return null;
  18. ListNode slow = head;
  19. ListNode fast = head.next;
  20. while (fast != null && fast.next != null) {
  21. slow = slow.next;
  22. fast = fast.next.next;
  23. }
  24. return slow;
  25. }
  26. private static ListNode reverse(ListNode head) {
  27. ListNode prev = null;
  28. while (head != null) {
  29. ListNode tmp = head.next;
  30. head.next = prev;
  31. prev = head;
  32. head = tmp;
  33. }
  34. return prev;
  35. }
  36. }

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/linear-list/linked-list/palindrome-linked-list.html