目录
一,题目描述
英文描述
中文描述
二,解题思路
递归
迭代(官方题解)
反转链表算法
反转算法应用
三,AC代码
C++
递归
迭代(官方题解)
四,解题过程
第一博
第二搏
一,题目描述
英文描述
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.
You may not alter the values in the list's nodes, only nodes themselves may be changed.
Example 1:
中文描述
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
进阶:
你可以设计一个只使用常数额外空间的算法来解决此问题吗?
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
示例 1:
二,解题思路
递归
和之前的反转链表前n个节点算法类似。但是一些细节部分需要注意。
以k=3为例。
设置虚拟头节点h;指针p初始指向h(用于标明待反转部分头节点的前驱节点);指针q初始指向h(用于遍历节点,标明节点个数是否满足k);指针tem指向p->next,当调用reverseN(p->next, 3)后,该节点将会成为下一待反转部分头节点的前驱节点;
q指针从从向尾遍历,达到k个节点时停止
调用reverseN(p->next, 3)
tem变成下k个待反转节点的头节点,因此将p、q指针更新为tem,重新进入下一轮循环
迭代(官方题解)
迭代解法也是分为两部分:反转链表算法,反转算法应用于k个节点。
反转链表算法
官方题解中用到的方法类似于尾插法,也就是不断将头节点插到尾部,具体可以看这里@&再见萤火虫&【LeetCode_LinkedList_206. Reverse Linked List 反转链表(C++/Java)【头插法,尾插法,递归】】
反转算法应用
也是通过计数的方法,当累计达到k个节点后,调用反转链表算法,然后将头节点替换为尾节点,尾节点继续向后遍历计数。
重复以上过程即可。
三,AC代码
C++
递归
/**
* Definition for singly-linked list.
* 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) {}
* };
*/
class Solution {
public:
ListNode* reverseN(ListNode* head, int n) {
if(n == 0 || n == 1) return head;
ListNode * tail = head->next, * h = reverseN(head->next, n - 1);
head->next = tail->next;
tail->next = head;
return h;
}
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* h = new ListNode;// 虚拟头节点
h->next = head;
int cnt = 0;// 记录节点个数判断是否满足反转条件
// p标记待反转部分的前一个节点
// q用于迭代过程,判定反转部分是否满足节点个数要求
// tem用于标记调用反转函数前,p后面一个节点,该节点将会成为下一次迭代的p
ListNode* p = h, *q = h, * tem = nullptr;
while(q != nullptr) {
if(cnt == k) {
tem = p->next;// 该节点将成为反转部分的尾节点,提前保存
p->next = reverseN(p->next, k);
cnt = 0;
// 重新调整p、q为下一待反转部分的前一个节点
p = tem;
q = tem;
} else {
q = q->next;
cnt++;
}
}
return h->next;
}
};
迭代(官方题解)
class Solution {
public:
// 翻转一个子链表,并且返回新的头与尾
pair<ListNode*, ListNode*> myReverse(ListNode* head, ListNode* tail) {
ListNode* prev = tail->next;
ListNode* p = head;
while (prev != tail) {
ListNode* nex = p->next;
p->next = prev;
prev = p;
p = nex;
}
return {tail, head};
}
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* hair = new ListNode(0);
hair->next = head;
ListNode* pre = hair;
while (head) {
ListNode* tail = pre;
// 查看剩余部分长度是否大于等于 k
for (int i = 0; i < k; ++i) {
tail = tail->next;
if (!tail) {
return hair->next;
}
}
ListNode* nex = tail->next;
tie(head, tail) = myReverse(head, tail);
pre->next = head;
tail->next = nex;
pre = tail;
head = tail->next;
}
return hair->next;
}
};
四,解题过程
第一博
用递归的方法试了试,效果不太稳定
第二搏
采用迭代的方法效果更好