LeetCode 234. 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?

 


题目标签: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/

 

posted @ 2017-12-02 11:30  Jimmy_Cheng  阅读(316)  评论(0编辑  收藏  举报