【题目链接】力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台,解题代码如下:
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode curNode = head;
ListNode groupHead, groupTail = head, lastGroupTail = null;
int len = 0;
while (curNode != null) {
curNode = curNode.next;
if (++len % k == 0) {
groupHead = reverseGroup(groupTail, curNode);
if (lastGroupTail != null) {
lastGroupTail.next = groupHead;
lastGroupTail = groupTail;
} else {
lastGroupTail = head;
head = groupHead;
}
groupTail = curNode;
}
}
lastGroupTail.next = groupTail;
return head;
}
private ListNode reverseGroup(ListNode head, ListNode tail) {
ListNode curNode = head, lastNode = null, nextNode;
while (curNode != tail) {
nextNode = curNode.next;
curNode.next = lastNode;
lastNode = curNode;
curNode = nextNode;
}
return lastNode;
}
【解题步骤】:
ListNode curNode = head;
ListNode groupHead, groupTail = head, lastGroupTail = null;
curNode = curNode.next;
if (++len % k == 0) {
groupHead = ListNode.reverseList(groupTail, curNode);
。。。
if (lastGroupTail != null) {
lastGroupTail.next = groupHead;
lastGroupTail = groupTail;
}
else {
lastGroupTail = head;
head = groupHead;
}
groupTail = curNode;
lastGroupTail.next = groupTail;
【思路总结】
1)首先要对复杂问题分解:再复杂的问题像“”庖丁解牛“”一样,找到其中脉络,进行分解之后,都会被切割成简单的个体小单元,很容易理解和掌握。
2)其次要学会“”依此类推“”的思路:算法的解决大数据的问题,基本都是找出其中规律,周而复始的进行重复性操作,直至结束:
3)最后处理一下开头、结尾或者空指针等特殊情况即可