一道leetcode习题的感想

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?

某个递归解法如下

虽然他是O(n)+O(n)但是灵活运用了栈,递归实现了验证思路足够新颖

如下压入所有--temp此时为head,遇到NULL出口pop一个,temp=temp->next;

验证一个解,pop一个,关键在于递归时没到出口全部入栈。

class Solution {
public:
ListNode* temp;
bool isPalindrome(ListNode* head) {
temp = head;
return check(head);
}

bool check(ListNode* p) {
if (NULL == p) return true;
bool isPal = check(p->next) & (temp->val == p->val);
temp = temp->next;
return isPal;
}
};

//////////////////////////////////////

我的解法

class Solution {
public:
bool isPalindrome(ListNode* head) {
//O(n)/O(1)
if(head==NULL)return true;
if(head->next==NULL)return true;
int count = 0;
auto p = head;
while(p)
{
count++;
p = p->next;
}
ListNode * tail = NULL;
p = head->next;
for(int i=0;i<count/2;i++)
{
head->next = tail;
tail = head;
head = p;
p = p->next;
}
////validate
int d= count/2;
if(count%2==1)
{
return va(d,p,tail);
}
else{
return va(d,head,tail);
}
}
bool va(int n,auto &l,auto &o)
{
for(int i=0;i<n;i++,o=o->next,l=l->next)
{
if(o->val != l->val)
return false;
}
return true;
}
};

//////反向部分链表,然后同步验证。

思路简单,实现时注意指针的位置,和两种情况区分好

posted on 2017-10-24 20:33  flyingwaters  阅读(118)  评论(0编辑  收藏  举报

导航