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;
}
相关推荐
Tomhex3 小时前
C语言内存安全防护指南
c语言
230万光年的思念5 小时前
zerotier连不上的问题
c语言
XiYang-DING8 小时前
【LeetCode】Hash | 136.只出现一次的数字
算法·leetcode·哈希算法
Fanfanaas8 小时前
Linux 基础开发工具(二)
linux·运维·服务器·c语言
leaves falling9 小时前
C/C++ const:修饰变量和指针的区别(和引用底层关系)
c语言·开发语言·c++
网域小星球9 小时前
C 语言从 0 入门(十二)|指针与数组:数组名本质、指针遍历数组
c语言·算法·指针·数组·指针遍历数组
Tairitsu_H9 小时前
C语言:排序(一)
c语言·数据结构·排序
12.=0.10 小时前
【stm32_5】Systick嘀嗒定时器、解析时钟源、分析时钟树、应用Systick设计延时
c语言·stm32·单片机·嵌入式硬件
嘻嘻哈哈樱桃10 小时前
俄罗斯套娃信封问题力扣--354
算法·leetcode·职场和发展
田梓燊10 小时前
2026/4/12 leetcode 1320
算法·leetcode·职场和发展