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 };

猜你喜欢

转载自www.cnblogs.com/joelwang/p/10519898.html