LeetCode/solutions/92. Reverse Linked List II.md
2019-03-24 23:39:01 +08:00

33 lines
1012 B
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [92. Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/)
# 思路
首先还是开辟一个真正的头结点real_head, 其next指针指向head。然后向后移动`m - 1`步到达需要翻转的第一个节点的前一个节点记为pre如果按照下面的例子的话
pre就指向1然后我们翻转pre后面的`n-m`个节点即可。
```
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
```
# C++
``` C++
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode *real_head = new ListNode(0);
real_head -> next = head;
ListNode *p, *pre = real_head, *tmp;
n -= m;
while(--m) pre = pre -> next;
p = pre -> next;
// reverse n-m nodes
while(n--){
tmp = p -> next;
p -> next = tmp -> next;
tmp -> next = pre -> next;
pre -> next = tmp;
}
return real_head -> next;
}
};
```