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);
}
相关推荐
CodeWithMe1 小时前
【C/C++】long long 类型传参推荐方式
c语言·开发语言·c++
NULL指向我2 小时前
C语言数据结构笔记6:使用宏和指针来设置和操作嵌套在结构体中的联合体数组的特定位
c语言·数据结构·笔记
whoarethenext3 小时前
使用 C/C++、OpenCV 和 Libevent 构建联网人脸识别考勤系统 [特殊字符]‍[特殊字符]
c语言·c++·opencv
GalaxyPokemon7 小时前
LeetCode - 2. 两数相加
java·前端·javascript·算法·leetcode·职场和发展
编程绿豆侠7 小时前
力扣HOT100之堆:347. 前 K 个高频元素
算法·leetcode·哈希算法
我不是加奈11 小时前
QMC5883L的驱动
c语言·驱动开发·单片机·嵌入式硬件
Coding小公仔11 小时前
LeetCode 240 搜索二维矩阵 II
算法·leetcode·矩阵
C++chaofan11 小时前
74. 搜索二维矩阵
java·算法·leetcode·矩阵
青小莫12 小时前
数据结构-C语言-链表OJ
c语言·数据结构·链表
Mi Manchi2612 小时前
力扣热题100之二叉树的层序遍历
python·算法·leetcode