25. K 个一组翻转链表 - 力扣(LeetCode) (leetcode-cn.com)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
private:
ListNode* reverse(ListNode* node) {
ListNode* tmp;
ListNode* prev = nullptr;
ListNode* cur = node;
while(cur) {
tmp = cur->next;
cur->next = prev;
prev = cur;
cur = tmp;
}
return prev;
}
public:
//递归
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* cur = head;
if(head == nullptr) return head;
for(int i = 0; i < k - 1; i++) {
cur = cur->next;
if(cur == nullptr)
return head;
}
ListNode* tmp = cur->next;
cur->next = nullptr;
//部分链表反转后的头节点
ListNode* newHead = reverse(head);
//递归
head->next = reverseKGroup(tmp, k);
return newHead;
}
};
修改问法:如果最后不满足k个的剩余节点也要反转呢?
修改一处即可
class Solution {
private:
ListNode* reverse(ListNode* node) {
ListNode* tmp;
ListNode* prev = nullptr;
ListNode* cur = node;
while(cur) {
tmp = cur->next;
cur->next = prev;
prev = cur;
cur = tmp;
}
return prev;
}
public:
//递归
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* cur = head;
if(head == nullptr) return head;
for(int i = 0; i < k - 1; i++) {
cur = cur->next;
if(cur == nullptr)
return reverse(head); //!!!!!!!!!!!!!!!!!这里返回的是反转后的头节点,而非原来的头节点
}
ListNode* tmp = cur->next;
cur->next = nullptr;
//部分链表反转后的头节点
ListNode* newHead = reverse(head);
//递归
head->next = reverseKGroup(tmp, k);
return newHead;
}
};
|