# 61. Rotate List

Reference: LeetCode
Difficulty: Medium

## Problem

Given a linked list, rotate the list to the right by $k$ places, where $k$ is non-negative ($k \geq 0$).

Note:

Example:

## Analysis

Methods:

• Calculate the length.
• Connect the last node to the head. Make a ring.
• Find the new tail, and return its next as a new head and set it null before returning.
• Time: $O(N)$
• Space: $O(1)$

## Code

Test Case:

Original version (struggled with corner cases):

Improvement:

Note:

• k could be greater than the length of the list. Do k % len.
• I can add if statement to return immediately if k equals 0 or len.
• But notice that you might have created the ring and you must set it null! Otherwise, it will return a ring causing infinitely looping. Memory Limit Exceeded
• Draw a graph for a simple case to see how many steps to go. Don’t just think!
• Counting templates:
• for: Use this one!
• while:

Here is the code I wrote in the second time. Forgot to restore the ring (I removed the bug already). Memory Limit Exceeded

Comment Junhao Wang
a software engineering cat