博客
关于我
链表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/

    你可能感兴趣的文章
    Notepad++在线和离线安装JSON格式化插件
    查看>>
    notepad++最详情汇总
    查看>>
    notepad++正则表达式替换字符串详解
    查看>>
    notepad如何自动对齐_notepad++怎么自动排版
    查看>>
    Notes on Paul Irish's "Things I learned from the jQuery source" casts
    查看>>
    Notification 使用详解(很全
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    NotImplementedError: Could not run torchvision::nms
    查看>>
    nova基于ubs机制扩展scheduler-filter
    查看>>
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    np.power的使用
    查看>>
    NPM 2FA双重认证的设置方法
    查看>>
    npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
    查看>>
    npm build报错Cannot find module ‘webpack‘解决方法
    查看>>
    npm ERR! ERESOLVE could not resolve报错
    查看>>
    npm ERR! fatal: unable to connect to github.com:
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
    查看>>