feat: 2025-10-29打卡
This commit is contained in:
48
25.reverse-nodes-in-k-group.java
Normal file
48
25.reverse-nodes-in-k-group.java
Normal file
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* @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
|
||||
|
||||
Reference in New Issue
Block a user