Author:赵志乾
Date:2020-02-22
Declaration:All Right Reserved!!!
题目描述:
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
示例:
给定这个链表:1->2->3->4->5
当 k = 2 时,应当返回: 2->1->4->3->5
当 k = 3 时,应当返回: 3->2->1->4->5
你的算法只能使用常数的额外空间。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
链表节点:
public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) { val = x; }
}
// 解法1
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
// step1: 增加哑节点简化代码
ListNode dummyNode = new ListNode(0);
dummyNode.next = head;
// step2: 外层标志量
ListNode curNode = dummyNode.next;
ListNode curPre = dummyNode;
// step3: 循环处理
while(shouldReverse(curNode,k)){
// step3.1: 内层反转标志量
ListNode innerPre = curNode;
ListNode innerCur = curNode.next;
// step3.2: 内层反转
for(int index=0;index<k-1;index++){
ListNode innerNext = innerCur.next;
innerCur.next = innerPre;
innerPre = innerCur;
innerCur = innerNext;
}
// step3.3: 完成反转
curPre.next = innerPre;
curNode.next = innerCur;
// step3.4: 外层迭代
curPre = curNode;
curNode = curNode.next;
}
return dummyNode.next;
}
private boolean shouldReverse(ListNode head, int k){
if(head==null){
return false;
}
ListNode curNode = head;
for(int index=0; index<k; index++){
if(curNode==null){
return false;
}
curNode = curNode.next;
}
return true;
}
}
注:链表类题目依然要画图帮助思考。如下图:
![](https://i-blog.csdnimg.cn/blog_migrate/3c5305a69513fbc419db88c9ee49c34b.jpeg)