leetcode hot100刷题日记——24.回文链表
解答:
class Solution {
public:ListNode* middle(ListNode* head){ListNode *slow=head,*fast=head;while(fast&&fast->next){slow=slow->next;fast=fast->next->next;}return slow;}ListNode*reverse(ListNode *mid){ListNode *pre=nullptr,*cur=mid;while(cur){ListNode *next=cur->next;cur->next=pre;pre=cur;cur=next;}return pre;}bool isPalindrome(ListNode* head) {//找中间节点,再反转右边链表ListNode *mid=middle(head);ListNode *head2=reverse(mid);while(head2){if(head2->val!=head->val){return false;}head=head->next;head2=head2->next;}return true;}
};
时间复杂度:O(n)
空间复杂度:O(1)