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;
}
相关推荐
caimouse21 小时前
ReactOS 窗口系统分析(25):标题栏显示与系统按钮 — nonclient.c 标题栏专题
c语言·开发语言
caimouse1 天前
ReactOS 窗口系统分析(14):计时器/属性/加速键/热键 — timer.c + prop.c + accelerator.c + hotkey.c
c语言·开发语言·reactos
水饺编程1 天前
第5章,[Win32 章节] :贝塞尔样条曲线(一)
c语言·c++·windows·visual studio
-凌凌漆-1 天前
【C语言】结构体typedef struct与struct的区别
c语言·开发语言
Nil2081 天前
leetcode 108有序数组转换为二叉搜索树
数据结构·算法·leetcode
hn小菜鸡1 天前
LeetCode 763、划分字母区间
数据结构·算法·leetcode
caimouse1 天前
ReactOS 窗口系统分析(24):输入法 — ime.c
c语言·reactos
ly76891 天前
C 语言从入门到进阶:语法、指针、内存管理与工程实践详解
c语言·开发语言
土司大王1 天前
LeetCode hot100——相交链表
算法·leetcode·链表
土司大王1 天前
LeetCode hot100——回文链表
算法·leetcode·链表