-
Notifications
You must be signed in to change notification settings - Fork 0
/
234.txt
55 lines (42 loc) · 1.16 KB
/
234.txt
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
/**
* 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;
ListNode* fast = head, *slow = head;
while(fast && fast->next){
slow = slow -> next;
fast = fast -> next -> next;
}
ListNode* right = revervse(slow);
ListNode* left = head;
while(right && left){
if (right -> val == left -> val){
right = right -> next;
left = left -> next;
}
else return false;
}
return true;
}
private:
ListNode* revervse(ListNode* begin){
ListNode* pre, *cur, *next;
pre = nullptr;
cur = begin;
while(cur){
next = cur -> next;
cur -> next = pre;
pre = cur;
cur = next;
}
return pre; // pre 返回最后一个结点, cur 返回null;
}
};