Given a singly linked list, determine if it is a palindrome.

Could you do it in O(n) time and O(1) space?

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
stack<ListNode*>s;
while(tmp != NULL) {
s.push(tmp);
tmp = tmp->next;
}
while(!s.empty()) {
ListNode* node = s.top();
s.pop();
}
return true;
}
};

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int count = 0;
while(tmp != NULL){
count++;
tmp = tmp->next;
}
int middle = count / 2;
ListNode* last = NULL;
for(int i = 0; i < middle; i++) {
last = tmp;
tmp = tmp->next;
}
if(count % 2) {
last = last->next;
tmp = tmp->next;
}
tmp = reverseList(tmp);
while(tmp != NULL) {
tmp = tmp->next;
}
return true;
}
ListNode* reverseList (ListNode * now) {
ListNode* past = NULL;
ListNode* future = now;
while(future != NULL) {
future = future->next;
now->next = past;
past = now;
now = future;
}
return past;
}
};
• 本文已收录于以下专栏：

举报原因： 您举报文章：[leetcode] 234.Palindrome Linked List 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)