--- tags: leetcode --- # [234. Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/) --- # My Solution ## Solution 1: Stack ### The Key Idea for Solving This Coding Question ### C++ Code ```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 == nullptr || head->next == nullptr) { return true; } stack<int> st; for (ListNode *it = head; it != nullptr; it = it->next) { st.push(it->val); } for (ListNode *it = head; it != nullptr; it = it->next) { if (st.top() != it->val) { return false; } st.pop(); } return true; } }; ``` ### Time Complexity $O(n)$ * $n$ is the number of nodes in the linked list. ### Space Complexity $O(n)$ ## Solution 2: Break the linked list ### The Key Idea for Solving This Coding Question ### C++ Code ```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 == nullptr || head->next == nullptr) { return true; } ListNode *preSlow = nullptr, *slow = head, *fast = head; while (fast != nullptr && fast->next != nullptr) { preSlow = slow; slow = slow->next; fast = fast->next->next; } ListNode *tmpHead = slow; preSlow->next = nullptr; ListNode *head2 = nullptr; while (tmpHead != nullptr) { ListNode *tmp = tmpHead->next; tmpHead->next = head2; head2 = tmpHead; tmpHead = tmp; } while (head != nullptr) { if (head->val != head2->val) { return false; } head = head->next; head2 = head2->next; } return true; } }; ``` ### Time Complexity $O(n)$ * $n$ is the number of nodes in the linked list. ### Space Complexity $O(1)$ # Miscellaneous <!-- # Test Cases ``` [1,2,2,1] ``` ``` [1,2] ``` ``` [3,3] ``` ``` [1] ``` ``` [1,2,4,2,1] ``` ``` [1,2,4,1,2] ``` ``` [1,2,1,2] ``` -->