請判斷一個鏈表是否爲迴文鏈表。
示例 1:
輸入: 1->2 輸出: false
示例 2:
輸入: 1->2->2->1 輸出: true
你能否用 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) {
int count=0;ListNode* p=head;
while(p!=NULL)
{
count++;
p=p->next;
}
if(count<=1)
return true;
int k=count/2;int w=count%2;
ListNode* myhead=new ListNode(0);
myhead->next=NULL;
ListNode* m=myhead;ListNode* q=head;
while(k>0)
{
m=q;
q=q->next;
m->next=myhead->next;
myhead->next=m;
k--;
}
if(w!=0)
q=q->next;
ListNode* t=myhead->next;
while(q!=NULL)
{
if(t->val==q->val)
{
q=q->next;
t=t->next;
}else{
return false;
}
}
return true;
}
};
如果有更好的方法,歡迎大家指正;