题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* reverseBetween(ListNode* head, int n) {
// write code here
auto* dummy = new ListNode(-1);
dummy->next = head;
auto pre = dummy;
head = pre->next;
for (int i = 1; i < n; ++i) {
auto next = head->next;
head->next = next->next;
next->next = pre->next;
pre->next = next;
}
return dummy->next;
}
ListNode* reverseKGroup(ListNode* head, int k) {
// write code here
int length = 0;
auto dummy = new ListNode(-1);//创建一个虚拟节点
auto dummy1 = dummy;//创建每一组翻转的虚拟节点
dummy->next = head;//让虚拟节点的next指向头节点,最后返回直接返回dummy->next
while (head != nullptr) {//先遍历链表,确定链表的长度
++length;
head = head->next;
}
auto times = static_cast<int>(length / k);//确定需要反转的组数
while (times--) {
auto pre = dummy1;//相当于将每一组链表独立出来,每一组的解法同BM2
head = pre->next;
for (int i = 1; i < k; ++i) {
auto next = head->next;
head->next = next->next;
next->next = pre->next;
pre->next = next;
}
dummy1 = head;//翻转以后,头节点必定是这一组节点的尾节点,同时也必定是下一组头节点的前驱节点
}
return dummy->next;
}
};
