题目描述
一开始自己写,只过了30个样例,总共40多个。因为没有讨论假如从头结点开始也就是left=1的情况。
以下为过了30多个样例的代码。
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
if(left == right) return head;
ListNode *prev = nullptr, *cur = head, *h1, *h2, *tail;
for(int i = 0; i < left - 2; i++) cur = cur -> next;
h1 = cur, cur = cur -> next, h2 = cur;
int cnt = right - left;
for(int i = 0; i < cnt + 1 && cur; i++) {
ListNode *next = cur -> next;
cur -> next = prev;
prev = cur, cur = next;
}
h1 -> next = prev, h2 -> next = cur;
return head;
}
};
以下为看了题解之后的代码,其实就加了一个 ListNode *dummy = new ListNode(-1);
以下为消耗的时间和空间
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
if(left == right) return head;
ListNode *dummy = new ListNode(-1);
dummy -> next = head;
ListNode *prev = nullptr, *cur = dummy, *h1, *h2, *tail;
for(int i = 0; i < left - 1; i++) cur = cur -> next;
h1 = cur, cur = cur -> next, h2 = cur;
int cnt = right - left;
for(int i = 0; i < cnt + 1 && cur; i++) {
ListNode *next = cur -> next;
cur -> next = prev;
prev = cur, cur = next;
}
h1 -> next = prev, h2 -> next = cur;
return dummy -> next;
}
};