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;
}
相关推荐
一去不复返的通信er2 小时前
力扣-图论-岛屿数量
算法·leetcode·图论
Xin7706 小时前
LeetCode 79. 单词搜索(DFS 回溯法)
leetcode
Zwawa7 小时前
编译器工具链:GCC、Clang、MSVC、ICC、armclang
c语言·嵌入式·编译器
学逆向的7 小时前
C 指针常量与常量指针
c语言·开发语言·网络安全
水饺编程8 小时前
第2章:Linux 基础,exit 命令
linux·c语言·汇编
shehuiyuelaiyuehao8 小时前
算法56,重排链表
数据结构·算法·链表
INGNIGHT10 小时前
440 · 背包问题(三)(无限次数)
算法·leetcode·动态规划
极客 - L U10 小时前
卡尔曼滤波从零到精通
c语言·数据结构·单片机·嵌入式硬件·mcu
Tisfy11 小时前
LeetCode 3619.总价值可以被 K 整除的岛屿数目:广度优先搜索BFS
算法·leetcode·bfs·宽度优先
谙弆悕博士12 小时前
用 C 写了个 Windows 聊天室,踩了几个多线程和控制台的坑
c语言·开发语言·c++·windows·网络编程·聊天室