1. 程式人生 > 其它 >【力扣 093】92. 反轉連結串列 II

【力扣 093】92. 反轉連結串列 II

92. 反轉連結串列 II

給你單鏈表的頭指標 head 和兩個整數 left 和 right ,其中 left <= right 。請你反轉從位置 left 到位置 right 的連結串列節點,返回 反轉後的連結串列 。
 

示例 1:


輸入:head = [1,2,3,4,5], left = 2, right = 4
輸出:[1,4,3,2,5]
示例 2:

輸入:head = [5], left = 1, right = 1
輸出:[5]
 

提示:

連結串列中節點數目為 n
1 <= n <= 500
-500 <= Node.val <= 500
1 <= left <= right <= n
 

進階: 你可以使用一趟掃描完成反轉嗎?

來源:力扣(LeetCode)
連結:https://leetcode.cn/problems/reverse-linked-list-ii
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

程式碼實現:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) 
    {
        if(!head) return head;
        ListNode *dumy = new ListNode(0), *p = dumy;
        dumy->next = head;
        for(int i = 0; i < m-1; ++i)
            p = p->next;

        ListNode *curr = p->next;
        for(int i = m; i < n; ++i)
        {
            ListNode *x = p->next;
            p->next = curr->next;
            curr->next = curr->next->next;
            p->next->next = x;

        }
        return dumy->next;
    }
};