您的位置:首页 > 其它

Leetcode Palindrome Linked List 234

2016-12-20 18:25 459 查看
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?

Subscribe to see which companies asked this question

题目链接

最开始考虑的是用栈来保存,时间和空间复杂度达到o(n)

/**
* 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==NULL) return true;

int cnt=0;
ListNode* p = head;
while(p){
cnt++;
p=p->next;
}
if(cnt==1) return true;
stack<int> s;

p = head;
int tmpcnt=0;
while(p){
tmpcnt++;
if(tmpcnt==cnt/2) {
s.push(p->val);
break;
}
else{
s.push(p->val);
}
p=p->next;
}

if(cnt%2) {
p=p->next->next;
}
else p=p->next;

while(p){
if(p->val==s.top()){
p=p->next;
s.pop();
}
else{
return false;
}
}
return true;
}
};


继续优化空间,达到常数空间

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
ListNode* he;
public:
bool isPalindrome(ListNode* head) {
if(head==NULL || head->next==NULL) return true;
else{
he=head;
return judge(he);
}
}

bool judge(ListNode* h){
if(h==NULL) return true;
if(!judge(h->next)) return false;

if(he->val!=h->val) return false;
else{
he=he->next;
return true;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: