Post

61 Rotate List

61 Rotate List

Rotate List image

Given the head of a linked list, rotate the list to the right by k places.

 

Example 1:

image

1
2
3
4
**Input:** head = [1,2,3,4,5], k = 2
**Output:** [4,5,1,2,3]

Example 2:

image

1
2
3
4
**Input:** head = [0,1,2], k = 4
**Output:** [2,0,1]

 

Constraints:

1
2
3
The number of nodes in the list is in the range [0, 500].
-100 <= Node.val <= 100
0 <= k <= 2 * 109
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

impl Solution {
    pub fn rotate_right(mut head: Option<Box<ListNode>>, k: i32) -> Option<Box<ListNode>> {
        
        let mut count = 0;
        let mut k_mut = k;
        let mut cursor = &head;
        loop {
            match cursor {
                Some(node) => {
                    cursor = &node.next;
                    count += 1;
                }, 
                None => {
                    break;
                }
            }
        }

        if count == 0 {
            return head
        }

        if k >= count {
            k_mut = k % count;
        }
        k_mut = count - k_mut;
        let mut temp = &mut head;
        while k_mut > 1 {
            match temp {
                Some(node) => {
                    temp = &mut node.next;
                    k_mut -= 1;
                }, 
                None => {
                    break;
                }
            }
        }
        let mut new_head = temp.as_mut().unwrap().next.take();
        temp.as_mut().unwrap().next = None;
        // need to append old head to end of new_head
        // find tail of new_head, then attach head
        let mut tail = &mut new_head;
        while let Some(node) = tail {
            if node.next.is_none() {
                node.next = head;
                return new_head;
            }
            tail = &mut node.next;
        }
        head
    }
}



This post is licensed under CC BY 4.0 by the author.