问题
LettCode25:给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。
k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
链接: 题目
例如:
输入:head = [1,2,3,4,5], k = 2
输出:[2,1,4,3,5]
将其分为两个链表一组,分为三组。
解题方法:
1.头插法
将链表分为三个部分
步骤如下:
代码
public static ListNode reverseKGroup(ListNode head, int k) {
if (head == null){
return null;
}
ListNode dumy = new ListNode();
dumy.next = head;
ListNode cur = head;
int leng = 0;
while (cur != null){
leng++;
cur = cur.next;
}
int n = leng/k;//计算出有几组
ListNode pre = dumy;
cur = head;
for (int i = 0; i < n; i++) {
for (int j = 0; j < k-1; j++) {
ListNode next = cur.next;
cur.next = cur.next.next;
next.next = pre.next;
pre.next = next;
}
pre = cur;
cur = cur.next;
}
return dumy.next;
}