思路
1.递归对每一组进行逆转。
2.参考答案。迭代完成每组逆转。0表示链表的头部,不包含数值。
0 1 2 3 4 5
0 2 1 3 4 5
0 3 2 1 4 5
0 4 3 2 1 5
0 5 4 3 2 1
通过一次迭代判断长度O(n),与边逆转边判断的时间复杂度一致。
3.关于递归与循环。递归思路简单,但编码容易出现问题,比如在本题中的两个last都要赋值。
4.当出现TLE的时候可能不是编写部分TLE,leetcode 中的隐藏代码也可能出现TLE。但都要仔细检查代码,必然是代码错误所致。
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include <cstdio>
class Solution {
public:
ListNode * nextgroup = new ListNode(0);
ListNode * empty_head = new ListNode(0);
ListNode *last = empty_head;
bool judge(ListNode * now,int k)
{
while(k --)
{
if(!now)return false;
now = now -> next;
}
return true;
}
ListNode * reserve(ListNode * now,int k)
{
if(k == 1)
{
last -> next = now;//本回合的last
nextgroup = now -> next;
return now ;
}
ListNode * nextt = reserve(now ->next,k - 1);
nextt -> next = now;
return now;
}
ListNode* reverseKGroup(ListNode* head, int k) {
last -> next = head;
if(k <= 1)return head;
int t = 0;
while(judge(last -> next,k))
{
last = reserve(last -> next,k);//下一回合的last
last -> next = nextgroup;
}
return empty_head -> next;
}
};
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
dummy -> next = head;
int len = length(head);
for (int i = 0; i < len / k; i++) {
pre -> next = head;
for (int j = 1; j < k; j++) {
ListNode* temp = pre -> next;
pre -> next = head -> next;
head -> next = head -> next -> next;
pre -> next -> next = temp;
}
pre = head;
head = head -> next;
}
return dummy -> next;
}
private:
ListNode *dummy = new ListNode(0), *pre = dummy;
int length(ListNode* head) {
int len = 0;
while (head) {
len++;
head = head -> next;
}
return len;
}
};