链表中的节点每k个一组翻转 C++
链表中的节点每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* reverseKGroup(ListNode* head, int k) {
// write code here
ListNode* Cur = head;
int iCount = 0;//元素总个数
while (Cur) {
iCount++;
Cur = Cur->next;
}
double iNum = iCount/k;//翻转组数
ListNode* List = head;
for (int i = 0; i < iNum; i++) {
head = reverseBetween(List, i*k+1, (i+1)*k);
List = head;
}
return head;
}
//翻转指定m-n的节点
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode* Cur = head;
ListNode* Next = nullptr;
ListNode* Nodem = head;
ListNode* Noden = head;
//保存m和n原位置的地址
for(int i = 0; i < m-1; i++) {
Nodem = Nodem->next;
}
for(int i = 0; i < n; i++) {
Noden = Noden->next;
}
//反转区间链表
Cur = Nodem;
ListNode* Pre = Noden;
for(int i = 0 ; i <= n-m ; i++){
Next = Cur->next;
Cur->next = Pre;
Pre = Cur;
Cur = Next;
}
//三表相连接
if (m == 1) {
return Pre;
}
Cur = head;
for(int i = 1; i < m-1; i++) {
Cur = Cur->next;
}
Cur->next = Pre;
return head;
}
};
查看26道真题和解析