单链表---回文结构

判断某一个单链表是否是回文结构,是返回true、不是返回false。

所谓的回文结构,就是类似对称结构:

对于奇数与偶数个结点均是如此。

那么就有思路:①找到链表的中间结点②逆置后半部分或前半部分③比较两者

①找中间结点:

cpp 复制代码
    ListNode* slow , *fast;
    fast = slow = head;
    while(fast&&fast->next)
    {
        fast=fast->next->next;
        slow=slow->next;
    }
    ListNode* mid = slow;

②逆置后半部分

可以使用三指针的方式进行逆置,也可以如上图所示创建一个指针变量midhead来头插。

cpp 复制代码
    //三指针逆置
    ListNode* mid = slow;
    while(mid->next)
    {
        ListNode* midnext = mid->next;
        ListNode* midnextnext = midnext->next;
        midnext->next = mid;
        mid = midnext;
    }
cpp 复制代码
    //逆置mid后的链表,采用头插
    ListNode* midhead = NULL;
    while(mid)
    {
        ListNode* midnext = mid->next;
        mid->next = midhead;
        midhead = mid;
        mid = midnext;
    }

③遍历比较两个链表同位置处的值

cpp 复制代码
    while(midhead&&head)
    {
        if(midhead->val!=head->val)
            return false;
        midhead=midhead->next;
        head=head->next;
    }
    return true;

整体代码如下:

cpp 复制代码
public:
    bool chkPalindrome(ListNode* head) {
        ListNode* slow , *fast;
        fast = slow = head;
        while(fast&&fast->next)
        {
            fast=fast->next->next;
            slow=slow->next;
        }
        ListNode* mid = slow;
        while(mid->next)
        {
            ListNode* midnext = mid->next;
            ListNode* midnextnext = midnext->next;
            midnext->next = mid;
            mid = midnext;
        }
        while(mid&&head)
        {
            if(mid->val!=head->val)
                return false;
            mid=mid->next;
            head=head->next;
        }
        return true;
    }
};
相关推荐
liulilittle16 分钟前
拥塞控制:排水终止的两种决策:OR 与 AND
网络·tcp/ip·计算机网络·算法·信息与通信·tcp·通信
花间相见25 分钟前
【LeetCode02】—— 两数之和:哈希表入门经典详解
数据结构·散列表
菜鸟‍33 分钟前
【论文学习】Segment Anything 分割一切
深度学习·学习·计算机视觉
weixin_307779131 小时前
从脚本执行到智能体协作:AI辅助测试能力的范式重构
运维·开发语言·人工智能·算法·测试用例
量化君也1 小时前
从回测到全自动实盘交易,全天候策略需要经历哪些改造?
大数据·人工智能·python·算法·金融
殇淋狱陌1 小时前
Python列表知识思维导图
开发语言·python·学习
fox_lht1 小时前
第十五章 函数式语言:迭代器和闭包
开发语言·后端·学习·算法·rust
LeeAmos11 小时前
Addendum No. 1 to JESD209-4 Low Power Double Data Rate 4X (LPDDR4X)的中文版
笔记
lpl3129055092 小时前
skynet 共享数据原理
服务器·c语言·lua
2301_775602382 小时前
食品安全法
学习