leetcode回文链表c++

回文链表

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true

进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?


解法1:

  • 将前半部分节点放入容器a中,将后半部分节点放入容器b中
  • 容器a正序与容器b倒序比较是否相等,不等则不是回文链表
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if(head==NULL || head->next==NULL)
            return true;
        vector a;
        vector b;
        int num=0;//存放链表长度
        ListNode *p=head;
        while(p)//计算链表长度
        {
            num++;
            p=p->next;
        }
        int midnum=num/2;
        p=head;
        for(int i=0;inext;
        }
        if(num%2==1)//若是奇数长度则省略最中间的元素
        {
            p=p->next;
        }
        for(int i=0;inext;
        }
        for(int i=0,j=midnum-1;i=0;i++,j--)
        {
            if(a[i].val!=b[j].val)
                return false;
        }
        return true;
    }
};

解法2:

  • 先用slow-fast指针法找到链表中点
  • 然后将链表后半部分反转
  • 最后判断两个链表是否相同
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if(head==NULL||head->next==NULL)
            return true;
        ListNode *slow=head;
        ListNode *fast=head;
        while(fast)
        {
            slow=slow->next;
            fast = fast->next ? fast->next->next: fast->next;
        }
        slow=rev(slow);
        while(head&&slow)
        {
            if(head->val!=slow->val)
                return false;
            else
            {
                head=head->next;
                slow=slow->next;
            }
        }
        return true;
    }
    ListNode* rev(ListNode* h)
    {
        if(h==NULL||h->next==NULL)
            return h;
        ListNode *p=rev(h->next);
        h->next->next=h;
        h->next=NULL;
        return p;
    }
};

你可能感兴趣的:(刷题,leetcode,乐乐的c++刷题之路)