Skip to content

Commit 69a0e8e

Browse files
committed
add 61
1 parent 4e5f15c commit 69a0e8e

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

S0061-rotate-list/src/main.rs

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,71 @@ fn main() {
4949
println!("{:?}", Solution::rotate_right(l, 1));
5050
}
5151

52+
/*
53+
// Definition for singly-linked list.
54+
// #[derive(PartialEq, Eq, Debug)]
55+
// pub struct ListNode {
56+
// pub val: i32,
57+
// pub next: Option<Box<ListNode>>
58+
// }
59+
//
60+
// impl ListNode {
61+
// #[inline]
62+
// fn new(val: i32) -> Self {
63+
// ListNode {
64+
// next: None,
65+
// val
66+
// }
67+
// }
68+
// }
69+
impl Solution {
70+
pub fn rotate_right(mut head: Option<Box<ListNode>>, k: i32) -> Option<Box<ListNode>> {
71+
use std::mem::swap;
72+
73+
let len = Solution::len(&head);
74+
if k == 0 || len == 0 || k as usize % len == 0 {
75+
return head;
76+
}
77+
78+
let mut node = &mut head;
79+
for _ in 0..(len - (k as usize % len) - 1) {
80+
if let Some(ref mut n) = node {
81+
node = &mut n.next;
82+
}
83+
}
84+
85+
let mut new_head = None;
86+
if let Some(ref mut node) = node {
87+
swap(&mut node.next, &mut new_head);
88+
}
89+
90+
// we have now cut the linked list in half
91+
// now we have to put it back together backwards
92+
93+
if let Some(ref mut new_head) = new_head {
94+
let mut node = new_head;
95+
while let Some(ref mut next) = node.next {
96+
node = next;
97+
}
98+
node.next = head;
99+
}
100+
101+
new_head
102+
}
103+
104+
fn len(head: &Option<Box<ListNode>>) -> usize {
105+
if let Some(ref n) = head {
106+
let mut len = 1;
107+
let mut node = n;
108+
while let Some(ref next) = node.next {
109+
len += 1;
110+
node = next;
111+
}
112+
len
113+
}
114+
else {
115+
0
116+
}
117+
}
118+
}
119+
*/

0 commit comments

Comments
 (0)