79人阅读 评论(0)

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;
}
};
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：51585次
• 积分：2793
• 等级：
• 排名：第12804名
• 原创：239篇
• 转载：0篇
• 译文：0篇
• 评论：5条
文章分类
最新评论