92. Reverse Linked List II
自己吭哧吭哧花了接近40分钟写完代码,AC后从评论区看到的解法,新增一个结点,方便处理从开头反转的情况,不用单独判断m==0进行特殊处理。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        n -= m;
        ListNode prehead(0);
        prehead.next = head;
        
        ListNode* pre = &prehead;
        while(--m)
            pre = pre->next;
    
        ListNode* pstart = pre->next;
        while(n--)
        {
            ListNode *temp = pstart->next;
            pstart->next = temp->next;
            temp->next = pre->next;
            pre->next = temp;
        }
        
        return prehead.next;
    }
};

一个可完整运行的实例,方便使用gdb调试。

#include <iostream>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
 };

ListNode* reverseBetween(ListNode* head, int m, int n) 
{
    n -= m;
    ListNode prehead(0);
    prehead.next = head;
    
    ListNode* pre = &prehead;
    while(--m)
        pre = pre->next;

    ListNode* pstart = pre->next;
    while(n--)
    {
        ListNode *temp = pstart->next;        
        pstart->next = temp->next;
        temp->next = pre->next;
        pre->next = temp;
    }
    //调试功能,打印链表所有元素
    for(ListNode * it = prehead.next;it != NULL;it = it->next)
        cout<<it->val<<endl;
    return prehead.next;
}
int main()
{
    ListNode last(5);
    ListNode fouth(4,&last);
    ListNode third(3,&fouth);
    ListNode second(2,&third);
    ListNode first(1,&second);
    reverseBetween(&first,2,4);

    return 0;
}

2021.02.27新增
迭代实现

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        ListNode* dummy = new ListNode(-1);
        dummy->next = head;
        
        ListNode* prev = dummy;
        
        for(int i = 1;i < left;i++)
        {
            prev = prev->next;
        }
        
        ListNode* curr = prev->next;
        
        for(int i = left;i < right;i++)
        {
            ListNode* next = curr->next;
            curr->next = next->next;
            next->next = prev->next;
            prev->next = next;
        }
        
        return dummy->next;
    }
};

递归实现: