https://leetcode.com/problems/palindrome-linked-list/description/
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?
time O(n) space:O(1)
(1) 先找中点
(2) 再reverse后半段
(3) 不用管两个子linked list的长度是否相等,从各个子链表的头开始一个一个比较。值不相等就返回false,相等就继续移动。
当取中点时,一定要 fast.next.next != null
1 public boolean isPalindrome(ListNode head) {
2 if (head == null) return true ;
3 ListNode fast = head , slow = head ;
4 ListNode mid = null ;
5 //step 1: find the middle node: when fast reaches the end, slow reaches the mid
6 //note: middle node has to be fast.next != null && fast.next.next != null
7 while (fast != null && fast.next != null && fast.next.next != null){
8 fast = fast.next.next ;
9 slow = slow.next ;
10 }
11 //ab' b''a mid == b'
12 mid = slow;
13 // secHalfHead == b''
14 ListNode secHalfHead = mid.next ;
15 //step 2: reverse the 2nd half
16 ListNode lastHead = reverse(secHalfHead) ;
17 //step 3: compare the 1st half with the 2nd half, if not the same return false
18 while (head != null && lastHead != null){
19 if (head.val != lastHead.val) {
20 return false ;
21 }
22 head = head.next ;
23 lastHead = lastHead.next ;
24 }
25 return true ;
26 }
27
28 /*1->2->3->4 to 1<-2<-3<-4
29 * p c
30 * */
31 private ListNode reverse(ListNode head){
32 ListNode pre = null ;
33 ListNode curr = head ;
34 while (curr!= null){
35 ListNode temp = curr.next ;
36 curr.next = pre ;
37 pre = curr ;
38 curr = temp;
39 }
40 return pre ;
41 }