234. Palindrome Linked List 發表於 2023-02-13 | 分類於 leetcode problemsolutionoption 1 - iterative12345678910111213141516171819202122class Solution {public: bool isPalindrome(ListNode* head) { // iterative + stack stack<int> sta; ListNode *slow = head, *fast = head; while(fast && fast->next){ slow = slow->next; fast =fast->next->next; } while(slow){ sta.push(slow->val); slow = slow->next; } fast = head; while(!sta.empty() && fast->val==sta.top()){ sta.pop(); fast = fast->next; } return sta.empty(); }}; option 2 - recursive1234567891011121314151617class Solution {public: ListNode *left; bool traverse(ListNode *right){ if(!right) return true; bool ret = traverse(right->next); if(left->val != right->val) return false; left = left->next; return ret ; } bool isPalindrome(ListNode* head) { // recursive left = head; return traverse(head); }}; analysis time complexity O(n) space complexity O(1)