1. 程式人生 > 實用技巧 >LeetCode234迴文連結串列

LeetCode234迴文連結串列

題目連結

https://leetcode-cn.com/problems/palindrome-linked-list/

題解一

  • 將連結串列元素存入陣列,然後從首尾遍歷
  • 注意如果是空連結串列,結果也是true
// Problem: LeetCode 234
// URL: https://leetcode-cn.com/problems/palindrome-linked-list/
// Tags: Linked List Two Pointers Recursion
// Difficulty: Easy

#include <iostream>
#include <vector>
using namespace std;

struct ListNode{
    int val;
    ListNode* next;
};

class Solution{
public:
    bool isPalindrome(ListNode* head) {
        // 儲存連結串列中的節點
        vector<int> vals;
        while(head != nullptr){
            vals.push_back(head->val);
            head = head->next;
        }
        // 從首尾兩側遍歷
        int front = 0, back = vals.size()-1;
        while(front < back){
            if(vals[front] != vals[back])
                return false;
            front++;
            back--;
        }
        return true;
    }
};

題解二

  • 遞迴寫法,有點牛的
// Problem: LeetCode 234
// URL: https://leetcode-cn.com/problems/palindrome-linked-list/
// Tags: Linked List Two Pointers Recursion
// Difficulty: Easy

struct ListNode{
    int val;
    ListNode* next;
};

class Solution{
private:
    ListNode* front;
    
    bool check(ListNode* node){
        if(node != nullptr){
            // 先檢查尾部
            if(!check(node->next)) return false;
            // 檢查當前節點
            if(node->val != this->front->val) return false;
            // 該節點檢查完了,遞迴使node從後往前,手動從前往後更新front
            this->front = this->front->next;
        }
        return true;
    }

public:
    bool isPalindrome(ListNode* head) {
        this->front = head;
        return this->check(head);
    }
};

作者:@臭鹹魚

轉載請註明出處:https://www.cnblogs.com/chouxianyu/

歡迎討論和交流!