【LeetCode】234. Palindrome Linked List (2 solutions)


Palindrome Linked List

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?

 

解法一:

一次遍歷,裝入vector,然后再一次遍歷判斷回文。

時間復雜度O(n),空間復雜度O(n)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        vector<int> v;
        while(head)
        {
            v.push_back(head->val);
            head = head->next;
        }
        for(int i = 0, j = v.size()-1; i < j; i ++, j --)
        {
            if(v[i] != v[j])
                return false;
        }
        return true;
    }
};

 

解法二:

找到鏈表中點,拆分后,逆轉后半個鏈表,然后兩個鏈表同時順序遍歷一次。

若鏈表長度為奇數,最末尾的元素可以忽略。

時間復雜度O(n),空間復雜度O(1)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if(head == NULL || head->next == NULL)
            return true;
        ListNode* mid = getMid(head);
        ListNode* head2 = reverse(mid);
        while(head && head2)
        {
            if(head->val != head2->val)
                return false;
            head = head->next;
            head2 = head2->next;
        }
        return true;
    }
    ListNode* getMid(ListNode* head)
    {// at least two nodes
        ListNode* slow = head;
        ListNode* fast = head;
        ListNode* preslow = NULL;
        do
        {
            fast = fast->next;
            if(fast)
            {
                fast = fast->next;
                preslow = slow;
                slow = slow->next;
            }
        }while(fast != NULL);
        preslow->next = NULL;
        return slow;
    }
    ListNode* reverse(ListNode* head)
    {
        if(head == NULL || head->next == NULL)
            return head;
        else if(head->next->next == NULL)
        {// two nodes
            ListNode* tail = head->next;
            head->next = NULL;
            tail->next = head;
            return tail;
        }
        else
        {
            ListNode* pre = head;
            ListNode* cur = pre->next;
            pre->next = NULL;   // set tail
            ListNode* post = cur->next;
            while(post)
            {
                cur->next = pre;
                pre = cur;
                cur = post;
                post = post->next;
            }
            cur->next = pre;
            return cur;
        }
    }
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM