题目:
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
Follow up:
Could you do it in O(n) time and O(1) space?
题目意思:
就是用O(1)的空间和O(n)的时间去解决链表的回文问题。
怎么做到O(1)了呢?那就只能逆置链表了,当链表长度为奇数和偶数的时候,分开处理。逆置链表选择头插法。反正做这个题恶心到我了。。
代码:
/**
* 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;
if(head->next==NULL) return true;
int cnt = 0;
ListNode* pHead = head;
ListNode *l,*q,*p,*pre;
bool ok = true;
while(pHead)
{
++cnt;
pHead = pHead->next;
}
if(cnt%2==1)
{
l = head;
int ite = cnt/2;
while(ite)
{
pre = l;
l = l->next;
--ite;
}
pre->next = NULL;
p = l->next;
l->next = NULL;
while(p)
{
q = p;
p = p->next;;
q->next = l->next;;
l->next = q;
}
l = l->next;
while(head)
{
int x = head->val;
int y = l->val;
if(x!=y)
{
ok = false;
break;
}
head = head->next;
l = l->next;
}
}
else
{
l = head;
int ite = cnt/2-1;
while(ite)
{
l = l->next;
--ite;
}
ListNode* pnew = new ListNode(0);
pnew->next = l->next;
l->next = NULL;
l = pnew;
p = l->next;
l->next = NULL;
while(p)
{
q = p;
p = p->next;;
q->next = l->next;;
l->next = q;
}
l = l->next;
while(head)
{
int x = head->val;
int y = l->val;
if(x!=y)
{
ok = false;
break;
}
head = head->next;
l = l->next;
}
}
return ok?true:false;
}
};