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 指针来找到中间点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution
{
public boolean isPalindrome(ListNode head)
{
ListNode slow = head;
ListNode fast = head;
ListNode tail; // find the middle
while(fast != null && fast.next != null)
{
slow = slow.next;
fast = fast.next.next;
} if(fast != null) // odd length
slow = slow.next; // move middle to right half // reverse right half
tail = reverse(slow); // compare head and tail
while(tail != null)
{
if(head.val != tail.val)
return false; head = head.next;
tail = tail.next;
} return true;
} private ListNode reverse(ListNode cursor)
{
ListNode pre = null;
ListNode next; while(cursor != null)
{
next = cursor.next;
cursor.next = pre;
pre = cursor;
cursor = next;
} return pre; // tail node
}
}
参考资料:https://discuss.leetcode.com/topic/33376/java-easy-to-understand
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/