博客
关于我
链表7-链表的回文结构
阅读量:149 次
发布时间:2019-02-27

本文共 1235 字,大约阅读时间需要 4 分钟。

为了判断链表是否为回文结构,可以使用以下方法:

  • 反转链表:通过快慢指针反转链表,防止链表成环。
  • 比较链表:比较原链表和反转后的链表是否相等。
  • 题目描述

    对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。

    给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。

    解题思路

    使用快慢指针反转链表,然后比较原链表和反转后的链表是否相等。

    class PalindromeList {    public:        bool chkPalindrome(ListNode* A) {            if (A == NULL || A->next == NULL) return true;            ListNode* slow = A;            ListNode* fast = A;            ListNode* prev = NULL;            while (fast && fast->next) {                prev = slow;                slow = slow->next;                fast = fast->next->next;            }            if (fast != NULL && fast->val != A->val) return false;            if (prev != NULL) prev->next = NULL;            ListNode* newhead = NULL, *cur = slow;            while (cur) {                ListNode* next = cur->next;                cur->next = newhead;                newhead = cur;                cur = next;            }            slow = newhead;            while (A) {                if (A->val != slow->val) return false;                A = A->next;                slow = slow->next;            }            return true;        }}
    这个方法的时间复杂度是O(n),额外空间复杂度为O(1)。通过快慢指针反转链表,防止链表成环,然后比较原链表和反转后的链表是否相等来判断是否为回文结构。

    转载地址:http://asbb.baihongyu.com/

    你可能感兴趣的文章
    python | aiofiles,一个超酷的 Python 库!
    查看>>
    python | akshare,一个超强的 开源Python 金融数据接口库!
    查看>>
    python | alabaster,一个强大的 关于alabaster 主题 Python 库!
    查看>>
    python | algorithms,一个超赞的 集合常用算法的Python 库!
    查看>>
    python调用jpype 报错:OSError JVM is already started和JVM cannot be restarted
    查看>>
    python | authlib,一个强大的 Python 库!
    查看>>
    python | awswrangler,一个高效的 Python 库!
    查看>>
    python | bashplotlib,一个有趣的Python库!
    查看>>
    python | bentoml,一个超级厉害的 模型部署 Python 库!
    查看>>
    python调用jar包的模块_python调用jar包
    查看>>
    python | black,一个神奇的 代码格式化工具 Python 库!
    查看>>
    python | bleach,一个超强的 Python 库!
    查看>>
    python | cartopy,一个有趣的 Python 库!
    查看>>
    python | cloud-init,一个实用的 云计算 Python 库!
    查看>>
    python | code2flow,一个神奇的 Python 库!
    查看>>
    python | cudf,一个超实用的 Python 库!
    查看>>
    python | daphne,一个非常nice的 Python 库!
    查看>>
    python调用halcon
    查看>>
    python | doit,一个非常实用的 Python 库!
    查看>>
    python | easyocr,一个超厉害的 关于OCR的 Python 库!
    查看>>