[LeetCode] Palindrome Linked List 迴文連結串列
阿新 • • 發佈:2018-12-27
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?
這道題讓我們判斷一個連結串列是否為迴文連結串列,LeetCode中關於迴文串的題共有六道,除了這道,其他的五道為 Palindrome Number 驗證迴文數字, Validate Palindrome 驗證迴文字串, Palindrome Partitioning 拆分迴文串,Palindrome Partitioning II 拆分迴文串之二 和 Longest Palindromic Substring 最長迴文串
解法一:
class Solution { public: bool isPalindrome(ListNode* head) { if (!head || !head->next) return true; ListNode *slow = head, *fast = head; stack<int> s; s.push(head->val); while (fast->next && fast->next->next) { slow= slow->next; fast = fast->next->next; s.push(slow->val); } if (!fast->next) s.pop(); while (slow->next) { slow = slow->next; int tmp = s.top(); s.pop(); if (tmp != slow->val) return false; } return true; } };
這道題的Follow Up讓我們用O(1)的空間,那就是說我們不能使用stack了,那麼如果代替stack的作用呢,用stack的目的是為了利用其後進先出的特點,好倒著取出前半段的元素。那麼現在我們不用stack了,如何倒著取元素呢。我們可以在找到中點後,將後半段的連結串列翻轉一下,這樣我們就可以按照迴文的順序比較了,參見程式碼如下:
解法二:
class Solution { public: bool isPalindrome(ListNode* head) { if (!head || !head->next) return true; ListNode *slow = head, *fast = head; while (fast->next && fast->next->next) { slow = slow->next; fast = fast->next->next; } ListNode *last = slow->next, *pre = head; while (last->next) { ListNode *tmp = last->next; last->next = tmp->next; tmp->next = slow->next; slow->next = tmp; } while (slow->next) { slow = slow->next; if (pre->val != slow->val) return false; pre = pre->next; } return true; } };