1. 程式人生 > >LC.234.Palindrome Linked List

LC.234.Palindrome Linked List

pri div public 鏈表 head node term desc leet

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,相等就繼續移動。

 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 while (fast != null && fast.next != null
){ 7 fast = fast.next.next ; 8 slow = slow.next ; 9 } 10 mid = slow ; 11 //step 2: reverse the 2nd half 12 ListNode lastHead = reverse(mid) ; 13 //step 3: compare the 1st half with the 2nd half, if not the same return false 14 while
(head != null && lastHead != null){ 15 if (head.val != lastHead.val) { 16 return false ; 17 } 18 head = head.next ; 19 lastHead = lastHead.next ; 20 } 21 return true ; 22 } 23 24 /*1->2->3->4 to 1<-2<-3<-4 25 * p c 26 * */ 27 private ListNode reverse(ListNode head){ 28 ListNode pre = null ; 29 ListNode curr = head ; 30 ListNode next = null ; 31 while (curr!= null){ 32 ListNode temp = curr.next ; 33 curr.next = pre ; 34 pre = curr ; 35 curr = temp; 36 } 37 return pre ; 38 }

LC.234.Palindrome Linked List