## [234\. Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/) Given the `head` of a singly linked list, return `true`_ if it is a _ _palindrome_ _ or _`false`_ otherwise_. **Example 1:** ![](https://assets.leetcode.com/uploads/2021/03/03/pal1linked-list.jpg) **Input:** head = \[1,2,2,1\] **Output:** true **Example 2:** ![](https://assets.leetcode.com/uploads/2021/03/03/pal2linked-list.jpg) **Input:** head = \[1,2\] **Output:** false **Constraints:** - The number of nodes in the list is in the range `[1, 105]`. - `0 <= Node.val <= 9` 判斷 linked list 是否有迴文 解法一:遞迴 ```cpp= /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: bool isPalindrome(ListNode* head) { ListNode* cur = head; return helper(head, cur); } bool helper(ListNode* head, ListNode*& cur) { if (!head) return true; bool res = helper(head->next, cur) && (cur->val == head->val); cur = cur->next; return res; } }; ``` :::success - 時間複雜度:$O(N)$ - 空間複雜度:$O(N)$ ::: ```cpp= /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: bool isPalindrome(ListNode* head) { if (!head || !head->next) return true; ListNode* slow = head; ListNode* fast = head; stack<int> stk; stk.push(head->val); while (fast->next && fast->next->next) { slow = slow->next; fast = fast->next->next; stk.push(slow->val); } if (!fast->next) stk.pop(); while (slow && slow->next) { slow = slow->next; int tmp = stk.top(); stk.pop(); if (tmp != slow->val) return false; } return true; } }; ``` :::success - 時間複雜度:$O(N)$ - 空間複雜度:$O(N)$ ::: 不用 stack,空間複雜度 $O(1)$ 的解法 ```cpp= ``` :::success - 時間複雜度:$O(N)$ - 空間複雜度:$O(1)$ :::