*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?

 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     /**
11      * @param head a ListNode
12      * @return a boolean
13      */
14     public boolean isPalindrome(ListNode head) {
15         if (head == null) {
16             return true;
17         }
18         
19         ListNode middle = findMiddle(head);
20         middle.next = reverse(middle.next);
21         
22         ListNode p1 = head, p2 = middle.next;
23         while (p1 != null && p2 != null && p1.val == p2.val) {
24             p1 = p1.next;
25             p2 = p2.next;
26         }
27         
28         return p2 == null;
29     }
30     
31     private ListNode findMiddle(ListNode head) {
32         if (head == null) {
33             return null;
34         }
35         ListNode slow = head, fast = head;
36         while (fast!=null&& fast.next != null && fast.next.next != null) {
37             slow = slow.next;
38             fast = fast.next.next;
39         }
40         
41         return slow;
42     }
43     
44     private ListNode reverse(ListNode head) {
45         ListNode prev = null;
46         ListNode current = head;
47         
48         while (current != null) {
49             ListNode temp = current.next;
50             current.next = prev;
51             prev = current;
52             current = temp;
53         }
54         
55         return prev;
56     }
57 }

reference: https://www.youtube.com/watch?v=sYcOK51hl-A

 
posted @ 2015-10-22 09:07  Hygeia  阅读(173)  评论(0编辑  收藏  举报