234. Palindrome Linked List

Total Accepted: 39482
Total Submissions: 145556
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?

Java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
 * 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) {
        int len = 0;
        ListNode p = head, tmp, newHead = null;
        while (p != null) {
            p = p.next;
            ++len;
        }
        p = head;
        int halfLen = len >>> 1;
        for (int i = 0; i < halfLen; ++i) {
            tmp = p.next;
            p.next = newHead;
            newHead = p;
            p = tmp;
        }
        if (len % 2 == 1) {
            p = p.next;
        }
        for (int i = 0; i < halfLen; ++i) {
            if (newHead.val != p.val)
                return false;
            newHead = newHead.next;
            p = p.next;
        }
        return true;
    }
}

打个小广告

欢迎加入我的小专栏「基你太美」一起学习。