@@ -49,3 +49,71 @@ fn main() {
49
49
println ! ( "{:?}" , Solution :: rotate_right( l, 1 ) ) ;
50
50
}
51
51
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