😴双指针+反转
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Solution { public: bool isPalindrome(ListNode* head) { if(!head || !head->next) return true; ListNode* slow = head, *fast = head, *pre = nullptr, *n; while(fast && fast->next) { n = slow; slow = slow->next; fast = fast->next->next;
n->next = pre; pre = n; } if(fast) slow = slow->next; while(slow && pre) { if(slow->val != pre->val) { return false; } slow = slow->next; pre = pre->next; } return true; } };
|
Accepted
26/26 cases passed (28 ms)
Your runtime beats 42.35 % of cpp submissions
Your memory usage beats 88.19 % of cpp submissions (12.4 MB)
😍stack
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| class Solution { public: bool isPalindrome(ListNode* head) { stack<int> stk; int count = 0; auto h = head; while(h) { h = h->next; ++count; } bool f = false; while(head) { if((stk.size() == count / 2) && (count % 2) && !f) { // cout << head->val << endl; head = head->next; f = true; continue; } int val = head->val; if(stk.size() && val == stk.top()) stk.pop(); else stk.push(val); head = head->next; } // cout << stk.size() << endl; return !stk.size(); } };
|
Accepted
26/26 cases passed (24 ms)
Your runtime beats 72.11 % of cpp submissions
Your memory usage beats 13.39 % of cpp submissions (13.4 MB)