题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
using System;
using System.Collections.Generic;
/*
public class ListNode
{
public int val;
public ListNode next;
public ListNode (int x)
{
val = x;
}
}
*/
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;
ListNode from = head;//第一个要反转的Node
ListNode to = head;//反转List的下一个
ListNode res = head;//结果
ListNode p1 = null;//from的前一个,用来连接。
int index = 1;//计数器
while (to != null)
{
from = head;
while (index < k) // k + 1 会 越 界
{
head = head.next;
index++;
if (head == null) break;
}
if(head == null)break;//return也行
to = head.next;
index = 1;
if (p1 == null) //设置初始值
{
res = process(from, to);
}
else
{
Console.WriteLine(p1.val);//测试用的不用管
p1.next = process(from, to);//链接反转后的List
}
p1 = from;
head = to;
}
return res;
}
//逆序
public ListNode process(ListNode from, ListNode to) {
ListNode p1 = null;
ListNode p2 = to;
while (from != to) {
p1 = from.next;
from.next = p2;
p2 = from;
from = p1;
}
return p2;
}
}

