C语言 | Leetcode C语言题解之第143题重排链表

题目:

题解:

cpp 复制代码
struct ListNode* middleNode(struct ListNode* head) {
    struct ListNode* slow = head;
    struct ListNode* fast = head;
    while (fast->next != NULL && fast->next->next != NULL) {
        slow = slow->next;
        fast = fast->next->next;
    }
    return slow;
}

struct ListNode* reverseList(struct ListNode* head) {
    struct ListNode* prev = NULL;
    struct ListNode* curr = head;
    while (curr != NULL) {
        struct ListNode* nextTemp = curr->next;
        curr->next = prev;
        prev = curr;
        curr = nextTemp;
    }
    return prev;
}

void mergeList(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* l1_tmp;
    struct ListNode* l2_tmp;
    while (l1 != NULL && l2 != NULL) {
        l1_tmp = l1->next;
        l2_tmp = l2->next;

        l1->next = l2;
        l1 = l1_tmp;

        l2->next = l1;
        l2 = l2_tmp;
    }
}

void reorderList(struct ListNode* head) {
    if (head == NULL) {
        return;
    }
    struct ListNode* mid = middleNode(head);
    struct ListNode* l1 = head;
    struct ListNode* l2 = mid->next;
    mid->next = NULL;
    l2 = reverseList(l2);
    mergeList(l1, l2);
}
相关推荐
H CHY2 分钟前
C++代码
c语言·开发语言·数据结构·c++·算法·青少年编程
alphaTao4 分钟前
LeetCode 每日一题 2025/12/22-2025/12/28
算法·leetcode
小小8程序员20 分钟前
除了 gcc/g++,还有哪些常用的 C/C++ 编译器?
c语言·开发语言·c++
小白菜又菜1 小时前
Leetcode 1523. Count Odd Numbers in an Interval Range
算法·leetcode
小白菜又菜2 小时前
Leetcode 944. Delete Columns to Make Sorted
算法·leetcode
Alex Cafu2 小时前
Linux网络编程1(OSI模型与TCP/IP协议栈)
linux·c语言·网络·tcp/ip
博语小屋2 小时前
转义字符.
c语言·c++
Tandy12356_4 小时前
手写TCP/IP协议栈——实现ping响应不可达
c语言·网络·c++·网络协议·tcp/ip·计算机网络
Swift社区4 小时前
LeetCode 458 - 可怜的小猪
算法·leetcode·职场和发展
程芯带你刷C语言简单算法题4 小时前
Day37~求组合数
c语言·开发语言·学习·算法·c