题目：Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of 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) {
/*ListNode *dummy=new ListNode(0);
ListNode *slow = dummy;
n -= m;
while (--m)
slow = slow->next;
ListNode *fast = slow->next, *tmp;
while (n--) {
tmp = fast->next;
fast->next = fast->next->next;
tmp->next = slow->next;
slow->next = tmp;
}
return dummy->next;*/

ListNode *dummy=new ListNode(0);

ListNode *slow=dummy;
n=n-m;//这一句话不能够放在下面循环的后面，因为m变了。
while(--m){
slow=slow->next;//在m个之前的一个
}

ListNode *fast=slow->next,*tmp;
while(n--){
tmp=fast->next;
fast->next=fast->next->next;

tmp->next= slow->next;
slow->next=tmp;
//fast=slow->next;
}
return dummy->next;
}
};

• 本文已收录于以下专栏：

LeetCode 92. Reverse Linked List II

1. 题目描述 Reverse a linked list from position m to n. Do it in-place and in one-pass. For examp...

Reverse a linked list from position m to n. Do it in-place and in one-pass. For example: Given 1...

leetcode -day30 Reverse Linked List II

1、 ﻿﻿ Reverse Linked List II  Reverse a linked list from position m to n. Do it in-place and in...

Reverse a linked list from position m to n. Do it in-place and in one-pass. For example: Given 1...

Reverse a linked list from position m to n. Do it in-place and in one-pass. For example: Given 1...

leetcode No92. Reverse Linked List II

Question: Reverse a linked list from position m to n. Do it in-place and in one-pass. For exam...