cpp
ListNode* reverseList(ListNode* head, ListNode* tail) {
ListNode* pre = nullptr;
ListNode* cur = head;
while (cur != tail) { 最后cur就是tail
ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode* dummyNode = new ListNode(0);
dummyNode->next = head;
ListNode* pre = dummyNode;
for (int i = 1; i < m; i++) {
pre = pre->next;
}
ListNode* start = pre->next;
ListNode* end = pre->next;
for (int i = m; i <= n; i++) {
end = end->next;
}
pre->next = reverseList(start, end);//执行这个函数以后start变成传过去的链表的尾节点,所以直接连接start和end就行
start->next = end;
return dummyNode->next;
}
cpp
ListNode* reverseList(ListNode* head, ListNode* tail) {
ListNode* pre = nullptr;
ListNode* cur = head;
while (cur != tail) {
ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
ListNode* reverseKGroup(ListNode* head, int k) {
// write code here
if (k == 1 || head->next == nullptr || head == nullptr) return head;
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* pre = dummy;
ListNode* start = pre->next;
ListNode* end = pre;
while (end->next != nullptr && end != nullptr) {
start = pre->next;
end = pre;
int i;
for (i = 0; i <= k; i++) {
if (end->next) end = end->next;
else {
end = nullptr;
break;
}
}
if (i < k) break;
else {
pre->next = reverseList(start, end);
start->next = end;
pre = start;
}
}
return dummy->next;
}