# 92. Reverse Linked List II

**<font color=red>难度: Medium</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/reverse-linked-list-ii/description/

> 内容描述

```
Reverse a linked list from position m to n. Do it in one-pass.

Note: 1 ≤ m ≤ n ≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
```

## 解题方案

> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******


难度:
Medium


跟 reverse linked list一样

思路： 找到 第 m 个node，然后开始reverse到第n个node，然后再把它们和原本的list连接起来

AC 代码

```python
class Solution(object):
    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        """
        if not head or m == n: 
            return head
        node_m_before = dummy = ListNode(-1)
        dummy.next = head
        
        for i in range(m-1):
            node_m_before = node_m_before.next

        prev = None
        cur = node_m_before.next
        node_m = node_m_before.next
        
        for i in range(n-m+1):
            nxt = cur.next
            cur.next = prev
            prev = cur
            cur = nxt

        node_m_before.next = prev
        node_m.next = cur

        return dummy.next 
```

> 思路 2
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******

看了一下别人的代码，又比我写的好嘛，因为是保证m和n有效，用的是for循环先找到 m node:

详细见[realisking](https://leetcode.com/problems/reverse-linked-list-ii/discuss/30709/Talk-is-cheap-show-me-the-code-(and-DRAWING))
```
for _ in range(m-1):
	....

for _ in range(n-m):
	reverse 操作
		
```
```python
class Solution(object):
    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        """
        if not head or m == n: 
            return head
        p = dummy = ListNode(None)
        dummy.next = head
        for i in range(m-1): 
            p = p.next
        tail = p.next

        for i in range(n-m):
            tmp = p.next                  
            p.next = tail.next            
            tail.next = tail.next.next    
            p.next.next = tmp            
        return dummy.next
```

