菜鸟成长逆袭之旅,爱好撸铁和撸代码,有强制的约束力,希望通过自己的努力做一个高品质人
Work together and make progress together
反转链表II
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
/**
* Definition for singly-linked 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(-1),*pre = dummy;
dummy->next = head;
for (int i = 0;i < m-1; ++i) pre = pre->next;
ListNode *cur = pre->next;
for (int i = m; i<n ;++i){
ListNode *t = cur->next;
cur->next = t->next;
t->next = pre->next;
pre->next = t;
}
return dummy->next;
}
};