标签:amp while tps markdown head AC release tis lse
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;
}
};
标签:amp while tps markdown head AC release tis lse
原文地址:https://www.cnblogs.com/zhchoutai/p/8901830.html