1. 程式人生 > >LeetCode 234. Palindrome Linked List (回文鏈表)

LeetCode 234. Palindrome Linked List (回文鏈表)

href http fas ava target 列表 listnode 一個 spa

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?


題目標簽:Linked List

  題目給了我們一個 linked list,讓我們判斷它是不是回文。

  這裏可以利用 #206 Reverse Linked List 把右邊一半的鏈表 倒轉,然後從左右兩頭開始比較鏈表是否是回文。

  這樣的話,首先要找到鏈表的中間點,然後開始倒轉右半邊鏈表。

  可以利用slow fast pointers 來找到中間點,當fast 走完的時候,slow 正好在中間。

Java Solution:

Runtime beats 39.01%

完成日期:06/11/2017

關鍵詞:singly-linked list

關鍵點:利用slow fast 指針來找到中間點

 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 class
Solution 10 { 11 public boolean isPalindrome(ListNode head) 12 { 13 ListNode slow = head; 14 ListNode fast = head; 15 ListNode tail; 16 17 // find the middle 18 while(fast != null && fast.next != null) 19 { 20 slow = slow.next;
21 fast = fast.next.next; 22 } 23 24 if(fast != null) // odd length 25 slow = slow.next; // move middle to right half 26 27 // reverse right half 28 tail = reverse(slow); 29 30 // compare head and tail 31 while(tail != null) 32 { 33 if(head.val != tail.val) 34 return false; 35 36 head = head.next; 37 tail = tail.next; 38 } 39 40 return true; 41 } 42 43 private ListNode reverse(ListNode cursor) 44 { 45 ListNode pre = null; 46 ListNode next; 47 48 while(cursor != null) 49 { 50 next = cursor.next; 51 cursor.next = pre; 52 pre = cursor; 53 cursor = next; 54 } 55 56 return pre; // tail node 57 } 58 }

參考資料:https://discuss.leetcode.com/topic/33376/java-easy-to-understand

LeetCode 題目列表 - LeetCode Questions List

題目來源:https://leetcode.com/

LeetCode 234. Palindrome Linked List (回文鏈表)