-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrotate_list.rs
84 lines (73 loc) · 1.9 KB
/
rotate_list.rs
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
///
/// Problem: Rotate List
///
/// Given the head of a linked list, rotate the list to the right by `k` places.
///
/// **Example 1:**
/// ```plaintext
/// Input: head = [1,2,3,4,5], k = 2
/// Output: [4,5,1,2,3]
/// Explanation: Rotating right by 2 shifts the last two elements to the front.
/// ```
///
/// **Example 2:**
/// ```plaintext
/// Input: head = [0,1,2], k = 4
/// Output: [2,0,1]
/// Explanation: Rotating right by 4 is equivalent to rotating by 1 (since k = 4 % 3).
/// ```
///
/// **Constraints:**
/// - `0 <= length of list <= 500`
/// - `-100 <= Node.val <= 100`
/// - `0 <= k <= 2 * 10^9`
///
/// # Solution:
/// - **Time Complexity:** `O(n)`
/// - **Space Complexity:** `O(1)`
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
// pub val: i32,
// pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
// #[inline]
// fn new(val: i32) -> Self {
// ListNode {
// next: None,
// val
// }
// }
// }
impl Solution {
pub fn rotate_right(head: Option<Box<ListNode>>, k: i32) -> Option<Box<ListNode>> {
if head.is_none() || head.as_ref()?.next.is_none() || k == 0 {
return head;
}
let mut length = 1;
let mut tail = head.as_ref()?;
while let Some(ref next) = tail.next {
tail = next;
length += 1;
}
let k = k as usize % length;
if k == 0 {
return head;
}
let mut head = head;
let mut new_tail = head.as_mut()?;
for _ in 0..(length - k - 1) {
new_tail = new_tail.next.as_mut()?;
}
let mut new_head = new_tail.next.take();
new_tail.next = None;
let mut temp = new_head.as_mut()?;
while temp.next.is_some() {
temp = temp.next.as_mut()?;
}
temp.next = head;
new_head
}
}