题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
http://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
先求出链表长度,得到需要翻转的次数(len/k)
调用翻转函数,进行翻转;
class Solution {
public:
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* revser(ListNode* head, int n) {
ListNode* newhead = new ListNode(-1);
ListNode* flag = head;
while (head&&n > 0) {
ListNode* temp = head->next;
head->next = newhead->next;
newhead->next = head;
head = temp;
n--;
}
flag->next = head;
return newhead->next;
}
ListNode* reverseKGroup(ListNode* head, int k) {
// write code here
ListNode* newhead = new ListNode(-1);
newhead->next = head;
ListNode* first = head;
int len = 0;
while (first) {
first = first->next;
len++;
}
first = newhead;
for (int i = 0; i < len / k; i++) {
ListNode* pre = first->next;
first->next = revser(first->next, k);
first = pre;
}
return newhead->next;
}
};牛客网编程题题解 文章被收录于专栏
本专栏记录在牛客网上AC的每一题,写下题解。 未来2年完成2000编程题的题解。 2021.12.29更新,最进准备毕设,断更了,会尽快做完毕设,继续做这一件事情
查看9道真题和解析