49 lines
1.2 KiB
Java
49 lines
1.2 KiB
Java
/*
|
|
* @lc app=leetcode id=25 lang=java
|
|
*
|
|
* [25] Reverse Nodes in k-Group
|
|
*/
|
|
|
|
// @lc code=start
|
|
/**
|
|
* 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) {
|
|
ListNode dummy = new ListNode(0), prev, frm, to;
|
|
dummy.next = head;
|
|
prev = dummy;
|
|
while(prev.next != null) {
|
|
frm = to = prev.next;
|
|
for(int i = 0; i<k-1; i++) {
|
|
if(to!=null) {
|
|
to = to.next;
|
|
}
|
|
}
|
|
if(to == null) {
|
|
// reach the end
|
|
break;
|
|
}
|
|
// reverse nodes in [frm, to]
|
|
ListNode cur = frm.next;
|
|
for(int i = 0; i<k-1; i++) {
|
|
frm.next = cur.next;
|
|
cur.next = prev.next;
|
|
prev.next = cur;
|
|
cur = frm.next;
|
|
}
|
|
prev = frm;
|
|
}
|
|
return dummy.next;
|
|
}
|
|
}
|
|
// @lc code=end
|
|
|