carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode92: Reverse Linked List II #287

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.

Example 1:

image

Input: head = [1,2,3,4,5], left = 2, right = 4 Output: [1,4,3,2,5]

Example 2:

Input: head = [5], left = 1, right = 1 Output: [5]

Constraints:

The number of nodes in the list is n. 1 <= n <= 500 -500 <= Node.val <= 500 1 <= left <= right <= n

carloscn commented 1 year ago

Analysis

image

局部的翻转链表。分为两个关键步骤比较难:

carloscn commented 1 year ago

code

int32_t reverse_between(LINKLIST_T *in_list, size_t left, size_t right)
{
    int32_t ret = 0;

    UTILS_CHECK_PTR(in_list);

    if (left > right || left == 0) {
        ret = -1;
        goto finish;
    }

    if (left == right) {
        goto finish;
    }

    size_t ln = left - 1;
    size_t rn = right - 1;
    LINKLIST_T *L = in_list, *R = in_list, *PR = NULL;

    // Find left header
    while (ln --) {
        L = L->next;
    }

    // Find right header
    while (rn --) {
        PR = R;
        R = R->next;
    }

    rn = right - left - 1;

    while (rn --) {
        ret = linklist_swap_value(L, R);
        UTILS_CHECK_RET(ret);

        L = L->next;
        R = PR;
        PR = in_list;
        while (PR->next != R) {
            PR = PR->next;
        }
    }

finish:
    return ret;
}
carloscn commented 1 year ago

code

https://review.gerrithub.io/c/carloscn/structstudy/+/556957 https://github.com/carloscn/structstudy/commit/6010dee400553337700992295a295dda65858aa3