题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
感觉这道题需要考虑的情况很多,
因为情况太多,导致代码太乱了, 估计需要参考其他人的看看。
大致逻辑是这样的。
封装一个递归方法,逻辑如下:
根据k的值遍历k-1次,获取一段数组最后一个节点。之后从这一段头节点开始遍历,把指针next指向前一个节点。直到遍历完成结束。
到最后,再次递归调用本方法,去处理下一段数组。把头节点的next指向递归方法的返回值节点。
最后当前方法的返回值是这一段数组的尾节点
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode reverseKGroup (ListNode head, int k) {
// write code here
if(k == 1)
{
return head;
}
return recursion(head,k);
}
public ListNode recursion(ListNode head,int k)
{
if(head==null)
{
return null;
}
ListNode tail = head;
//获取每一节的尾巴,如果长度不够则证明是最后一节
for(int i=0;i<k-1;i++)
{
tail = tail.next;
if(tail==null){
return head;
}
}
ListNode end = tail.next ;
ListNode tmp ;
ListNode tmp2 ;
ListNode tmp3 ;
tmp = head;
tmp2 = head.next;
tmp3 = tmp2.next;
head.next = null;
while(tmp2!=end)
{
tmp2.next = tmp;
tmp=tmp2;
tmp2 = tmp3;
if(tmp3!=null)
{
tmp3 =tmp3.next;
}
}
head.next = recursion(end,k);
return tail;
}
}
查看21道真题和解析