Total Accepted: 28267
Total Submissions: 113712
Difficulty: Easy
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?
Subscribe to see which companies asked this question
思路:
1.用一个“快”指针(fast)和“慢”指针(slow),同时后移。两个指针的后移速度是:fast = 2*slow,即slow走一步,fast走两步。
2.slow指针最终的位置链表的中间位置。
3.将前半部分链表逆置。
4.比较两个部分。
code:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null) {
return true;
}
ListNode slow = head;
ListNode fast = head;
ListNode p = slow.next;
ListNode pre = slow;
//find mid pointer, and reverse head half part
while(fast.next != null &&fast.next.next != null) {
fast = fast.next.next;
pre = slow;
slow = p;
p = p.next;
slow.next = pre;
}
//odd number of elements, need left move slow one step
if(fast.next == null) slow = slow.next;
slow = slow.next;
p = p.next;
}
return true;
}
}