Leetcode 61. Rotate List

Problem

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

Algorithm

In each rotate step, the last item will get to the front the the list.
So each n step get the same value with the inital one and k is as the same as k % n.
Then put the last k item in front of the list.

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        if not head or not k:
            return head
        
        sL = 0
        p = head
        value = []
        while p:
            value.append(p.val)
            sL += 1
            p = p.next
            
        if sL == 1:
            return head
            
        k = (sL - k % sL) % sL
        p = head
        while p:
            p.val = value[k]
            p = p.next
            k = (k+1) % sL
            
        return head

你可能感兴趣的:(解题报告)