描述
将给出的链表中的节点每 k 个一组翻转,返回翻转后的链表
如果链表中的节点数不是 k 的倍数,将最后剩下的节点保持原样
你不能更改节点中的值,只能更改节点本身。
示例1
输入: {1,2,3,4,5},2
返回值: {2,1,4,3,5}
示例2
输入: {},1
返回值: {}
思路:
先反转一组(反转链表),然后使用递归反转剩下的。
递归三段式:
确定递归函数的参数和返回值
确定终止条件
确定单层递归的逻辑
1、每次进入函数的头节点遍历链表k次,分出一组,若是后续不足K个节点,不用反转直接返回头
ListNode3* tail = head;
for (int i = 0; i < k; i++)
{
if (tail == NULL)return head;
tail = tail->next;
}
2、将分出来的链表反转
3、链表反转后,原来的头变成了尾,后面接下一组的反转结果,下一组采用上述递归继续
ListNode3* res = reverseList(head,tail);
head->next = reverseKGroup(tail, k);
完整代码
#include<iostream>
using namespace std;
struct ListNode3{
int val;
ListNode3* next;
ListNode3(int x=0):val(x),next(NULL){}
};
ListNode3* createList()
{
ListNode3* dummy = new ListNode3();
ListNode3* temp = NULL;
ListNode3* tail = dummy;
int a = 0;
while (true)
{
cin >> a;
temp = new ListNode3(a);
tail->next = temp;
tail = tail->next;
if (cin.get() == '\n')
break;
}
return dummy->next;
}
void printList(ListNode3* head)
{
ListNode3* cur = head;
while (cur)
{
cout << cur->val << ',';
cur = cur->next;
}
cout << endl;
}
ListNode3* reverseList(ListNode3* left,ListNode3* right)
{
ListNode3* pre = NULL;
ListNode3* cur = left;
while (cur!= right)
{
ListNode3* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
ListNode3* reverseKGroup(ListNode3* head, int k)
{
ListNode3* tail = head;
for (int i = 0; i < k; i++)
{
if (tail == NULL)return head;
tail = tail->next;
}
ListNode3* res = reverseList(head,tail);
head->next = reverseKGroup(tail, k);
return res;
}
int main()
{
int k = 0;
while(true)
{
ListNode3* head = createList();
cin >> k;
ListNode3* res = reverseKGroup(head, k);
printList(res);
}
return 0;
}