---
# System prepended metadata

title: 0092. Reverse Linked List II
tags: [Leetcode, Linked List, Medium]

---

# 0092. Reverse Linked List II
###### tags: `Leetcode` `Medium` `Linked List`
Link: https://leetcode.com/problems/reverse-linked-list-ii/

## 思路
将需要reverse的部分截下来，做完reverse之后，再装回去
## Code
```c=
/**
 * 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 {
private:
   void reverse_linkedlist(ListNode* head){
       ListNode* pre = new ListNode; 
       while(head != nullptr){
           ListNode* next = head->next;
           head->next = pre;
           pre = head;
           head = next;
        }
        
    }
public:
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        ListNode *dummy_head = new ListNode(-1);
        dummy_head->next = head;
        
        ListNode *pre = dummy_head;
        for(int i = 0;i < left-1;i++){
            pre = pre->next;
        }
        
        ListNode *rightNode = pre;
        for(int i = 0;i < right-left+1;i++){
            rightNode = rightNode->next;
        }
        
        ListNode *leftNode = pre->next;
        ListNode *tail = rightNode->next;
        
        pre->next = nullptr;
        rightNode->next = nullptr;
        
        reverse_linkedlist(leftNode);
        
        pre->next = rightNode;
        leftNode->next = tail;
        
        return dummy_head->next;
    }
};
```
## Result
Runtime: 4 ms, faster than **54.17%** of C++ online submissions for Reverse Linked List II.
Memory Usage: 7.4 MB, less than **91.71%** of C++ online submissions for Reverse Linked List II.
