Leetcode234(力扣234):回文链表

Leetcode234(力扣234):回文链表_第1张图片
方法一:将链表value全部放入栈中再利用栈的逆序性弹出比较,复杂度较高

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) 
    {
        stack<int> s;
        ListNode *p=head;
        while(p)
        {
            s.push(p->val);
            p=p->next;
        }
        p=head;
        while(p)
        {
            if(p->val!=s.top()) return 0;
            s.pop();
            p=p->next;
        }
        return 1;
    }
};

Leetcode234(力扣234):回文链表_第2张图片方法二:进阶解法要求O(1)的空间复杂度,栈的方法显然不可行。可以想办法找到链表的中点然后将后半部分翻转再与前半部分进行比较。
注意:题中出现中点或者倍数的问题可以考虑使用快慢指针解决

class Solution 
{
public:
    bool isPalindrome(ListNode* head) 
    {
        if(!head||!(head->next)) return 1;
        ListNode* fast=head;
        ListNode* slow=head;
        while(fast&&fast->next)
        {
            slow=slow->next;
            fast=fast->next->next;
        }
        ListNode* cur=slow;
        ListNode* pre=slow->next;
        while(pre)
        {
            ListNode* temp=pre->next;
            pre->next=cur;
            cur=pre;
            pre=temp;
        }
        slow->next=nullptr;
        while(head&&cur)
        {
            if(head->val!=cur->val) return 0;
            head=head->next;
            cur=cur->next;
        }
        return 1;
    }
};

Leetcode234(力扣234):回文链表_第3张图片复杂度还是很高。。。。不知道为啥。。。。

你可能感兴趣的:(链表,leetcode,算法,单链表)