Leetcode Palindrome Linked List

OpenSoucre發表於2015-08-02

Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?

題目意思:

  給定一個單連結串列,判斷它是不是迴文串

  進一步思考:

    你可以在O(n)時間複雜度和O(1)空間複雜度完成嗎?

解題思路:

方法一:通過反轉連結串列實現

  (1)使用快慢指標尋找連結串列中點

  (2)將連結串列的後半部分就地逆置

  (3)比較前後兩半的元素是否一致

  (4)恢復原始連結串列的結構

方法二:通過遞迴實現

  (1)遞迴遍歷連結串列到最後一個元素

  (2)如果第一個元素和最後一個元素相等,則遞迴回退,且第一個元素left=left->next

  (3)如果所有元素相等,則認為是迴文串

原始碼:

方法一:

 1 class Solution {
 2 public:
 3     bool isPalindrome(ListNode* head) {
 4         if(head == NULL || head->next == NULL ) return true;
 5         ListNode* fast = head, *slow = head;
 6         while(fast->next && fast->next->next){
 7             fast = fast->next->next;
 8             slow = slow->next;
 9         }
10         ListNode *p = slow->next, *second = NULL;
11         while(p){
12             ListNode* tmp = p->next;
13             p->next = second;
14             second = p;
15             p = tmp;
16         }
17         ListNode* p1 = head, *p2 = second;
18         while(p2 && p1->val == p2->val){
19             p1 = p1->next;
20             p2 = p2->next;
21         }
22         p = second; second = NULL;
23         while(p  ){
24             ListNode *tmp = p->next;
25             p->next = second;
26             second = p;
27             p = tmp;
28         }
29         return p2 == NULL ;
30     }
31 };

方法二:

 1 class Solution {
 2 public:
 3     bool isPalindrome_aux(ListNode** left, ListNode* right){
 4             if(right == NULL) return true;
 5             if(!isPalindrome_aux(left,right->next)) return false;
 6             bool res = (right->val == (*left)->val);
 7             *left = (*left)->next;
 8             return res;
 9         
10     }
11     bool isPalindrome(ListNode* head) {
12         return isPalindrome_aux(&head,head);
13     }
14 };

 

 

  

相關文章