Given a singly linked list, determine if it is a palindrome.
简单的使用栈,检测是否回文
/**
* 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||head->next==NULL){
return 1;
}
ListNode* p=head;
int n=0;
while(p){
n++;
p=p->next;
}
stack<int> st;
int m=n/2;
p=head;
while(m--){
st.push(p->val);
p=p->next;
}
if(n%2==1){
p=p->next;
}
while(p){
if(p->val==st.top()){
st.pop();
p=p->next;
}else{
return false;
}
}
if(st.empty()){
return true;
}else
return false;
}
};
另一种方法满足O(n)和O(1),但效果并不怎么样,还会破坏链表结构。方法:在链表一半的时候反转链表,在比较两个链表,两段链表尾部要指向空,或者增加计数,否则容易在一直循环。
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head==NULL||head->next==NULL){
return 1;
}
ListNode* p=head;
int n=0;
while(p){
n++;
p=p->next;
}
int m=n/2;
p=head;
while(m--){
p=p->next;
}
if(n%2==1){
p=p->next;
}
ListNode* q=p->next;
p->next=NULL;
ListNode* tmp;
while(q){
tmp=q->next;
q->next=p;
p=q;
q=tmp;
}
q=head;
while(p&&q){
if(p->val!=q->val)
return false;
p=p->next;
q=q->next;
}
return true;
}
};