LeetCode 0061. Rotate List Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0061. Rotate List

Description

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

 

Example 1:

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

Example 2:

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

 

Constraints:

  • The number of nodes in the list is in the range [0, 500].
  • -100 <= Node.val <= 100
  • 0 <= k <= 2 * 109

Solutions

Solution 1: Fast and Slow Pointers + Link List Concatenation

First, we check whether the number of nodes in the linked list is less than 2. If so, we directly return head.

Otherwise, we first count the number of nodes n in the linked list, and then take the modulus of k by n to get the effective value of k.

If the effective value of k is 0, it means that the linked list does not need to be rotated, and we can directly return head.

Otherwise, we use fast and slow pointers, let the fast pointer move k steps first, and then let the fast and slow pointers move together until the fast pointer moves to the end of the linked list. At this time, the next node of the slow pointer is the new head node of the linked list.

Finally, we concatenate the linked list.

The time complexity is O(n), where n is the number of nodes in the linked list. The space complexity is O(1).

PythonJavaC++GoTypeScriptRustC#
# 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: Optional[ListNode], k: int) -> Optional[ListNode]: if head is None or head.next is None: return head cur, n = head, 0 while cur: n += 1 cur = cur.next k %= n if k == 0: return head fast = slow = head for _ in range(k): fast = fast.next while fast.next: fast, slow = fast.next, slow.next ans = slow.next slow.next = None fast.next = head return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !