1、题目:
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
2、解答:主要思路是"两两交换",画图便可知道代码的意思。
3、C++代码:
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *pre = dummy;
for(int i=0;i<m-1;i++){
pre = pre->next;
}
ListNode *curr = pre->next;
for(int i=0;i<n-m;i++){
ListNode *temp = curr->next;
curr->next = temp->next;
temp->next = pre->next;
pre->next = temp;
}
return dummy->next;
}
};
python代码:
class Solution:
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
dummy = ListNode(0)
dummy.next = head
pre = dummy
for i in range(0,m-1):
pre = pre.next
curr = pre.next
for i in range(0,n-m):
temp = curr.next
curr.next = temp.next
temp.next = pre.next
pre.next = temp
return dummy.next