leetcode 回文二叉树

 

 

C++最简单的方法,遍历存在vector<int> ivec容器中,然后头尾对应比较

O(n)时间,O(n)空间

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool isPalindrome(ListNode* head) {
12         if(head==NULL) return true;
13         ListNode* cur=head;
14         vector<int> ivec;
15         while(cur){
16             ivec.push_back(cur->val);
17             cur=cur->next;
18         }
19         for(int i=0;i<ivec.size()-1-i;i++){
20             int j=ivec.size()-1-i;
21             if(ivec[i]!=ivec[j]) return false;
22         }
23         return true;
24     }
25 };

 

C++进阶方法:使用O(n)时间,O(1)空间,对前一半元素链表指向进行翻转,然后从中间到两边遍历判断,缺点是更改了原来的链表,好处是没有占用额外存储空间;

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool isPalindrome(ListNode* head) {
12         if(head==NULL||head->next==NULL) return true;
13         ListNode* cur,*pre;
14         cur=head;
15         int length=0;
16         while(cur!=NULL){
17             length+=1;
18             cur=cur->next;
19         }
20         cur=head->next;pre=head;head->next=NULL;
21         for(int i=1;i<(length+1)/2;i++){
22                 ListNode* temp;
23                 temp=cur->next;
24                 cur->next=pre;
25                 pre=cur;
26                 cur=temp;
27         }
28         if(length%2==1) pre=pre->next;
29         while(cur!=NULL){
30             if(cur->val==pre->val){
31                 cur=cur->next;pre=pre->next;
32             }
33             else return false;
34         }
35         return true;
36     }
37 };

 

转载于:https://www.cnblogs.com/joelwang/p/10519898.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值