思路:日常递归
每k个完成操作,递归一次
# include<iostream>
# include<vector>
# include<string>
# include<algorithm>
# include<math.h>
# include<climits>
# include<stack>
# include<queue>
using namespace std;
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) {}
};
ListNode* DIGUIreverseKGroup(ListNode* head, int k) {
int num=0;
ListNode* p=head;//游标
ListNode* s;//反转链尾
ListNode* sh;//反转链头
if (!head)return head;//空表
if (head && k <= 1)return head;
while (p&&num<k) {
num++;
p = p->next;
}
if (num < k)
return head;//说明结点数不够
else {//说明节点数够的
s = head;//反转后的尾巴
sh = head;
p = head->next;//游标
num = 1;
while (num < k) {
num++;
head = p->next;
p->next = sh;
sh = p;
p = head;
}//反转
s->next = DIGUIreverseKGroup(head, k);
return sh;//新头
}
}
ListNode* reverseKGroup(ListNode* head, int k) {
head = DIGUIreverseKGroup(head, k);
return head;
}
int main(void) {
ListNode* head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
head = reverseKGroup(head, 1);//k可以随便改 1就是k
ListNode* p = head;
while (p) {
cout << p->val << " ";
p = p->next;
}
cout << endl;
system("pause");
return 0;
}