LeetCode 234 Palindrome Linked List

137 阅读1分钟

LeetCode 234 Palindrome Linked List

思路

  1. 遍历链表,将所有元素放入vector中,然后从两边开始向中间遍历vector。

  2. 找到链表的中点,然后将前半部分反转。LeetCode 206 Reverse Linked List

代码

方法1

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        vector<int> v;
        
        while (head) {
            v.push_back(head->val);
            head = head->next;
        }
        
        int left = 0, right = v.size() - 1;
        while (left < right) {
            if (v[left] != v[right]) return false;
            else {
                ++left;
                --right;
            }
        }
        
        return true;
    }
};

方法2

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        ListNode *slow = head, *fast = head, *preHead = nullptr;
        
        while (fast && fast->next) {
            fast = fast->next->next;
            ListNode *nextSlow = slow->next;
            slow->next = preHead;
            preHead = slow;
            slow = nextSlow;
        }
        
        if (fast) slow = slow->next;
        
        while (slow) {
            if (slow->val != preHead->val) return false;
            else {
                slow = slow->next;
                preHead = preHead->next;
            }
        }
        
        return true;
    }
};