卖萌的弱渣

I am stupid, I am hungry.

Rotate List

Rotate List

Given a list, rotate the list to the right by k places, where k is non-negative.

Example

Given 1->2->3->4->5 and k = 2, return 4->5->1->2->3.

Solution

  • Time: O(n)
(Rotate-List.py) download
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
# Definition for singly-linked list.
class ListNode:
     def __init__(self, x):
         self.val = x
         self.next = None

class Solution:
    # @param head: the list
    # @param k: rotate to the right k places
    # @return: the list after rotation
    def rotateRight(self, head, k):
        # write your code here
        if head == None or k == 0 or head.next == None:
            return head

        dummy_node = ListNode(-1)
        dummy_node.next = head
        new_head = dummy_node.next
        next_node = dummy_node.next

        # find the length of the list
        len = 1
        while next_node.next != None:
            len += 1
            next_node = next_node.next

        # find the pos
        pos = k % len
        if pos == 0:
            return head

        # find the new head
        while len-pos > 1:
            new_head = new_head.next
            pos += 1

        result = new_head.next
        new_head.next = None

        # connect old tail with old head
        next_node.next = dummy_node.next
        return result

if __name__ == "__main__":
    sol = Solution()
    node1 = ListNode(1)
    node2 = ListNode(2)
    node3 = ListNode(3)
    node4 = ListNode(2)
    node5 = ListNode(1)
    node1.next=node2
    node2.next=node3
    node3.next=node4
    node4.next=node5
    sol.rotateRight(node1,1)