
顺序:橙色->红色->蓝色->紫色
/*** 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(0);dummy->next = head;auto left = dummy, right = head;int cnt = m - 1;while(cnt--){left = right;right = right->next;}auto savehead = left;auto savetail = right;left = right;right = right->next;cnt = n - m;while(cnt--){auto nxt = right->next;right->next = left;left = right;right = nxt;}savehead->next = left;savetail->next = right;return dummy->next;}};
递归
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if(!head || m == n) return head;
auto dummy = new ListNode(0);
dummy->next = head;
auto prev = dummy;
int move = m - 1;
while(move--)
{
prev = prev->next;
}
auto tail = prev->next;
move = n - m;
while(move--)
{
auto tmp = tail->next;
tail->next = tmp->next;
tmp->next = prev->next;
prev->next = tmp;
}
return dummy->next;
}
};
第二次写题
/**
* 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);
dummy->next = head;
ListNode* prev = dummy;
for(int i = 0; i < m - 1; i++)
prev = prev->next;
ListNode *tail = prev->next;
// cout << prev->val << endl;
for(int i = m; i < n; i++)
{
ListNode* cur = tail->next;
tail->next = cur->next;
cur->next = prev->next;
prev->next = cur;
}
return dummy->next;
}
};
