25. Reverse Nodes in k-Group Hard
1/**
2 * [25] Reverse Nodes in k-Group
3 *
4 * Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.
5 * k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.
6 * You may not alter the values in the list's nodes, only nodes themselves may be changed.
7 *
8 * Example 1:
9 * <img alt="" src="https://assets.leetcode.com/uploads/2020/10/03/reverse_ex1.jpg" style="width: 542px; height: 222px;" />
10 * Input: head = [1,2,3,4,5], k = 2
11 * Output: [2,1,4,3,5]
12 *
13 * Example 2:
14 * <img alt="" src="https://assets.leetcode.com/uploads/2020/10/03/reverse_ex2.jpg" style="width: 542px; height: 222px;" />
15 * Input: head = [1,2,3,4,5], k = 3
16 * Output: [3,2,1,4,5]
17 *
18 *
19 * Constraints:
20 *
21 * The number of nodes in the list is n.
22 * 1 <= k <= n <= 5000
23 * 0 <= Node.val <= 1000
24 *
25 *
26 * Follow-up: Can you solve the problem in O(1) extra memory space?
27 *
28 */
29pub struct Solution {}
30use crate::util::linked_list::{ListNode, to_list};
31
32// problem: https://leetcode.com/problems/reverse-nodes-in-k-group/
33// discuss: https://leetcode.com/problems/reverse-nodes-in-k-group/discuss/?currentPage=1&orderBy=most_votes&query=
34
35// submission codes start here
36
37// Definition for singly-linked list.
38// #[derive(PartialEq, Eq, Clone, Debug)]
39// pub struct ListNode {
40// pub val: i32,
41// pub next: Option<Box<ListNode>>
42// }
43//
44// impl ListNode {
45// #[inline]
46// fn new(val: i32) -> Self {
47// ListNode {
48// next: None,
49// val
50// }
51// }
52// }
53impl Solution {
54 pub fn reverse_k_group(head: Option<Box<ListNode>>, k: i32) -> Option<Box<ListNode>> {
55 Some(Box::new(ListNode::new(0)))
56 }
57}
58
59// submission codes end
60
61#[cfg(test)]
62mod tests {
63 use super::*;
64
65 #[test]
66 fn test_25() {
67 }
68}
69
Back
© 2025 bowen.ge All Rights Reserved.