题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* reverseKGroup(ListNode* head, int k) {
// write code here
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* p = dummyHead, * q = dummyHead;
int step;
while (true) {
q = p;
for (step = k; q->next != nullptr && step != 0; step--) q = q->next;
if (step != 0) return dummyHead->next;
ListNode* pre = q->next, * cur = p->next;
while (pre != q) {
ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
p->next = q;
for (step = k; p->next != nullptr && step != 0; step--) p = p->next;
}
}
};
查看11道真题和解析
