leetcode做题笔记92. 反转链表 II

给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。

示例 1:

leetcode做题笔记92. 反转链表 II_第1张图片

思路一:头插法

struct ListNode *reverseBetween(struct ListNode *head, int left, int right) {
    struct ListNode *dummyNode = malloc(sizeof(struct ListNode));
    dummyNode->val = -1;
    dummyNode->next = head;

    struct ListNode *pre = dummyNode;
    for (int i = 0; i < left - 1; i++) {
        pre = pre->next;
    }
    struct ListNode *cur = pre->next;
    struct ListNode *next;
    for (int i = 0; i < right - left; i++) {
        next = cur->next;
        cur->next = next->next;
        next->next = pre->next;
        pre->next = next;
    }
    return dummyNode->next;
}

 分析:

本题根据left值将指针移动到目标节点前一位,再通过头插法将节点反转,最后返回链表

总结:

本题考察链表的应用,运用头插法更改节点顺序即可解决

你可能感兴趣的:(链表,leetcode,笔记,链表)