Problem
Problem page: https://leetcode.com/problems/rotate-list/
Topics: Linked List, Two Pointers
Difficulty: Medium
Similar problems: (E) Rotate Array
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.
Analysis
Problems like this one, where you reverse a linked list or part of one, are routine exercises in a college data structures course. There are generally three things to watch for:
- Set up pointers at head/tail as needed to make the list easier to work with.
- Handle special cases such as when the number of nodes n is 0, 1, or 2. Remember to check whether a pointer is None.
- Sometimes head or tail needs special handling. You can add a new_head or new_tail so you can treat head or tail like any other node.
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-rotate-list/
