1. 程式人生 > >leetcode 234 回文鏈表 Palindrome Linked List

leetcode 234 回文鏈表 Palindrome Linked List

clas temp head 長度 style 時間復雜度 etc src +=

技術分享圖片

要求用O(n)時間,和O(1)空間,因此思路是用本身鏈表進行判斷,既然考慮回文,本方法思想是先遍歷一次求鏈表長度,然後翻轉前半部分鏈表;然後同時對前半部分鏈表和後半部分鏈表遍歷,來判斷對應節點的值是否對應相等,時間復雜度應該為O(2n),空間復雜度O(3);基本符合要求,但是運行時間還是有點長;

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

技術分享圖片

leetcode 234 回文鏈表 Palindrome Linked List