1. 程式人生 > >【LeetCode & 劍指offer刷題】連結串列題11:Palindrome Linked List

【LeetCode & 劍指offer刷題】連結串列題11:Palindrome Linked List

【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...)

Palindrome Linked List

Given a singly linked list, determine if it is a palindrome. Example 1: Input: 1->2 Output: false Example 2: Input: 1->2->2->1 Output: true
Follow up: Could you do it in O(n) time and O(1) space?   /**  * Definition for singly-linked list.  * struct ListNode {  *     int val;  *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}  * };  */ /* 問題:判斷是否為迴文連結串列 方法:用快慢指標法找到連結串列中部位置,然後翻轉右半連結串列,判斷右邊連結串列與左邊連結串列是否相等 O(n),O(1) */ class Solution { public
:     bool isPalindrome ( ListNode * head )     {         if (! head || ! head -> next ) return true ; //異常情況處理,為空結點或者一個結點時                       ListNode * slow = head , * fast = head ;         while ( fast && fast->next ) // 快慢指標法,讓 slow 指向連結串列中部位置         {             slow = slow -> next ;             fast = fast -> next -> next ;         } // 退出時, fast為最後一個結點或者nullslow處在中間位置(與結點數有關,左子連結串列head~slow-1, 右子連結串列為slow~end,右子連結串列比左子連結串列長一或者相等)         // 例: 0~10,slow 5, fast 10; 0~9,slow5,fast null (0 表示頭結點, slow fast 的起點 )                 ListNode * right = reverseList (slow); //反轉右邊連結串列         ListNode * left = head ;                 while ( left && right ) //比較左右子連結串列是否相等         {             if ( left -> val == right -> val )             {                 left = left -> next ;                 right = right -> next ;             }             else                 return false ;                     }                 return true ;             }     //函式:反轉連結串列     ListNode * reverseList ( ListNode * head )     {         if ( head == nullptr ) return nullptr ;                ListNode * pre = nullptr , * cur = head ,* next ; // 三個指標分別儲存之前,當前,下一個結點         while ( cur )         {             next = cur -> next ; // 儲存原連結串列該結點的下一個結點,以免變換指向之後無法遍歷到下一個結點             cur -> next = pre ; // 變換指向                        pre = cur ; // 更新指標             cur = next ; // 更新指標         }         return pre ; // 最後 pre 指向最後一個結點, cur 指向 null     } };