题目
给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。
k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
示例 1:
输入:head = [1,2,3,4,5], k = 2
输出:[2,1,4,3,5]
解
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
int count = 0;
ListNode pre = dummy;
ListNode cur = head;
ListNode next = null;
while (cur != null) {
next = cur.next;
count++;
if (count == k) {
ListNode p1 = pre.next;
ListNode p2 = cur;
p2.next = null;
reverse(p1);
pre.next = p2;
p1.next = next;
pre = p1;
count = 0;
}
cur = next;
}
return dummy.next;
}
public void reverse(ListNode head) {
if (head == null || head.next == null) {
return;
}
ListNode pre = null;
ListNode cur = head;
ListNode next = null;
while (cur != null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
}
}