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);
}
相关推荐
叫我辉哥e15 小时前
### 技术文章大纲:C语言造轮子大赛
c语言·开发语言
TracyCoder1236 小时前
LeetCode Hot100(15/100)——54. 螺旋矩阵
算法·leetcode·矩阵
进击的小头8 小时前
行为型模式:策略模式的C语言实战指南
c语言·开发语言·策略模式
爱编码的小八嘎9 小时前
C语言对话-5.通过任何其他名字
c语言
weixin_4454766810 小时前
leetCode每日一题——边反转的最小成本
算法·leetcode·职场和发展
打工的小王10 小时前
LeetCode Hot100(一)二分查找
算法·leetcode·职场和发展
Swift社区10 小时前
LeetCode 385 迷你语法分析器
算法·leetcode·职场和发展
定偶11 小时前
C语言入门指南
c语言·开发语言
期末考复习中,蓝桥杯都没时间学了11 小时前
力扣刷题10
算法·leetcode·职场和发展
的卢马飞快12 小时前
【C语言进阶】给数据一个“家”:从零开始掌握文件操作
c语言·网络·数据库