|
| 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