leetcode解题: Palindrome Linked List (234)

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?

解法1: O(N) Time + O(1) Space

基本思路就是从中间断开,然后把其中一段reverse,再同时遍历判断两个字列是否一致。
C++

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head || !head->next) {
return true;
}
int count = 0;
ListNode* ptr = head;
while (ptr) {
++count;
ptr = ptr->next;
}
ptr = head;
ListNode* preMidPtr = preMid(ptr);
ListNode* right;
if (count % 2 == 0) {
// even number
right = preMidPtr->next;
preMidPtr->next = NULL;
} else {
right = preMidPtr->next->next;
preMidPtr->next = NULL;
}
right = reverse(right);
while (head && right) {
if (head->val != right->val) {
return false;
}
head = head->next;
right = right->next;
}
return head == NULL && right == NULL;
}
ListNode* preMid(ListNode* root) {
ListNode* fast = root->next;
while (fast && fast->next && fast->next->next) {
root = root->next;
fast = fast->next->next;
}
return root;
}
ListNode* reverse(ListNode* head) {
ListNode* prev = NULL;
while (head) {
ListNode* temp = head->next;
head->next = prev;
prev = head;
head = temp;
}
return prev;
}
};

Java

1