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?
思路:
把链表一分为二,把右边的一半翻转,再逐个比对左右的链表即可。
/**
* 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||!head->next){
return true;
}
ListNode *p,*pre,*q;
p=head;
q=head;
pre=NULL;
while(q){
q=q->next;
if(!q){
break;
}
pre=p;
p=p->next;
q=q->next;
}
pre->next=NULL;
ListNode *r=reverse(p);
p=head;
q=r;
while(p&&q){
if(p->val!=q->val){
return false;
}
p=p->next;
q=q->next;
}
return true;
}
ListNode* reverse(ListNode *head){
ListNode *h=NULL;
ListNode *p=head;
ListNode *tail=NULL;
while(p){
ListNode *next=p->next;
p->next=NULL;
if(!h){
h=p;
}else{
p->next=h;
h=p;
}
p=next;
}
return h;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-12-28 18:19:05