LeetCode LCR027.回文链表 C写法

LeetCode 027.回文链表 C写法

思路🧐:

​ 快慢指针+反转链表,通过快慢指针找到中间结点,再将中间结点后的所有结点反转。如果是回文链表那么中间结点往后的值与头结点到中间结点的值都相等,如果有不相等的就不是回文链表。

代码✨:

c 复制代码
 struct ListNode* MidNode(struct ListNode* head) //找中间结点
 {
    struct ListNode* fast = head;
    struct ListNode* slow = head;
    while(fast && fast->next)
    {
        fast = fast->next->next;
        slow = slow->next;
    }
    return slow;
 }
 struct ListNode* Reverse(struct ListNode* midhead) //链表反转
 {
    struct ListNode* rhead = NULL;
    struct ListNode* cur = midhead;
    while(cur)
    {
        struct ListNode* tail = cur->next;
        cur->next = rhead;
        rhead = cur;
        cur = tail;
    }
    return rhead;
 }


bool isPalindrome(struct ListNode* head){
    struct ListNode* cur = head;
    struct ListNode* mid = MidNode(head);
    struct ListNode* midhead = Reverse(mid);
    while(cur != mid) //当cur走到mid结点处就结束
    {
        if(cur->val != midhead->val) //如果不相等就返回false
        {
            return false;
        }
        else //如果相等就继续往后走
        {
            cur = cur->next;
            midhead = midhead->next;
        }
    }
    return true;
}
相关推荐
小溪学编程10 小时前
C语言篇:枚举类型
java·c语言·前端
小溪学编程10 小时前
C语言篇:语言结构
c语言·开发语言·算法
老王爱玩车10 小时前
字符串和字符串函数
c语言·开发语言·数据结构·学习
山下梅子酒22510 小时前
洛谷-入门-B2082
c语言
圣保罗的大教堂11 小时前
leetcode 3532. 针对图的路径存在性查询 I 中等
leetcode
白山编程大哥11 小时前
C语言篇:可变参数函数
c语言·开发语言
水饺编程11 小时前
第1章:开发环境搭建,在 Windows 中安装 VS 2019
linux·c语言·汇编·visual studio
ebiobiz12 小时前
Zig 嵌入式底层库选择与 build.zig 组织指南
c语言·c++·嵌入式硬件·mcu
longlongzihan1 天前
从LeetCode 70. 爬楼梯看动态规划:如何精准推导状态转移方程?
c++·算法·leetcode·动态规划
程序员清风1 天前
算法与数据结构入门:复杂度、数组与链表
数据结构·算法·链表