leetcode 25 K 个一组翻转链表
1.给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
2.k 是一个正整数,它的值小于或等于链表的长度。
3.如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
示例:
给你这个链表:1->2->3->4->5
当 k = 2 时,应当返回: 2->1->4->3->5
当 k = 3 时,应当返回: 3->2->1->4->5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode ReverseKGroup(ListNode head, int k) {
if (head == null) return null;
var pre = head;
var last = head;
int index = 0;
while (index < k)//last右移k,遇空结束
{
if (last.next == null && index < k - 1)
{
return pre;
}
last = last.next;
index++;
}
var tail = head;
//头插法
while (pre != last)
{
var t = pre;
pre = pre.next;
t.next = head;
head = t;
}
tail.next = ReverseKGroup(last, k);
return head;
}
}