
正文
leetcode 回文二叉树
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
C++最简单的方法,遍历存在vector<int> ivec容器中,然后头尾对应比较
O(n)时间,O(n)空间
/**
* 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;
ListNode* cur=head;
vector<int> ivec;
while(cur){
ivec.push_back(cur->val);
cur=cur->next;
}
for(int i=;i<ivec.size()--i;i++){
int j=ivec.size()--i;
if(ivec[i]!=ivec[j]) return false;
}
return true;
}
};
C++进阶方法:使用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||head->next==NULL) return true;
ListNode* cur,*pre;
cur=head;
int length=;
while(cur!=NULL){
length+=;
cur=cur->next;
}
cur=head->next;pre=head;head->next=NULL;
for(int i=;i<(length+)/;i++){
ListNode* temp;
temp=cur->next;
cur->next=pre;
pre=cur;
cur=temp;
}
if(length%==) pre=pre->next;
while(cur!=NULL){
if(cur->val==pre->val){
cur=cur->next;pre=pre->next;
}
else return false;
}
return true;
}
};






