-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathreverse_nodes_in_k_group.rs
More file actions
54 lines (45 loc) · 1.31 KB
/
reverse_nodes_in_k_group.rs
File metadata and controls
54 lines (45 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#[allow(dead_code)]
struct Solution;
// Definition for singly-linked list.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
#[inline]
#[allow(dead_code)]
fn new(val: i32) -> Self {
ListNode { next: None, val }
}
}
impl Solution {
#[allow(dead_code, clippy::needless_pass_by_value)]
pub fn reverse_k_group(head: Option<Box<ListNode>>, k: i32) -> Option<Box<ListNode>> {
let mut head = head;
// Try to traverse forward k steps
let mut node = &mut head;
for _ in 0..k {
match node {
Some(n) => {
node = &mut n.next;
}
_ => return head,
}
}
// Get the rest of the list reversed
let new_head = Self::reverse_k_group(node.take(), k);
// Now reverse this part of the list and connect it to the head returned from the rest of
// the list
let mut node = head;
let mut prev_node = new_head;
for _ in 0..k {
let mut current = node.unwrap();
let next_node = current.next;
current.next = prev_node;
prev_node = Some(current);
node = next_node;
}
prev_node
}
}