Skip to content

Commit e4c6e2b

Browse files
committed
add 61
1 parent 71a0fdc commit e4c6e2b

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

S0061-rotate-list/Cargo.toml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
[package]
2+
name = "S0061-rotate-list"
3+
version = "0.1.0"
4+
authors = ["xargin <cao1988228@163.com>"]
5+
edition = "2018"
6+
7+
[dependencies]

S0061-rotate-list/src/main.rs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
use leetcode_prelude::*;
2+
struct Solution;
3+
4+
use std::mem::replace;
5+
// Definition for singly-linked list.
6+
impl Solution {
7+
pub fn rotate_right(mut head: Option<Box<ListNode>>, k: i32) -> Option<Box<ListNode>> {
8+
if head.is_none() || head.as_ref().unwrap().next.is_none() || k == 0 {
9+
return head;
10+
}
11+
let mut cursor = &mut head;
12+
// count len
13+
let mut len = 0;
14+
while cursor.as_ref().is_some() {
15+
len += 1;
16+
cursor = &mut cursor.as_mut().unwrap().next;
17+
}
18+
19+
let (k, mut cnt) = (len-k % len, 0);
20+
cursor = &mut head;
21+
22+
loop {
23+
if cnt == k {
24+
let mut target = replace(cursor, None);
25+
// find the tail
26+
let mut tail = &mut target;
27+
while tail.is_some() {
28+
tail = &mut tail.as_mut().unwrap().next;
29+
}
30+
// now tail is None
31+
// replace it to head
32+
// set the tail.next = head
33+
replace(tail, head);
34+
return target;
35+
}
36+
cursor = &mut cursor.as_mut().unwrap().next;
37+
cnt += 1;
38+
}
39+
40+
}
41+
}
42+
43+
fn main() {
44+
let l = linkedlist![1, 2, 3, 4, 5];
45+
println!("{:?}", Solution::rotate_right(l, 2));
46+
let l = linkedlist![0,1,2];
47+
println!("{:?}", Solution::rotate_right(l, 4));
48+
let l = linkedlist![1,2];
49+
println!("{:?}", Solution::rotate_right(l, 1));
50+
}
51+

0 commit comments

Comments
 (0)