PU Rotate List

Jan 01, 1970

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

Example:

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

C Solution:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* rotateRight(struct ListNode* head, int k) {
    if (!head) return 0;
    struct ListNode *tail = head;
    int len = 1;
    while (tail->next) {
        len++;
        tail = tail->next;
    }
    k %= len;
    if (!k) return head;
    k = len - k;
    tail->next = head;
    while (--k) head = head->next;
    tail = head->next;
    head->next = 0;
    return tail;
}

Python Solution:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head: return
        count = 1
        tail = head
        while tail.next:
            count += 1
            tail = tail.next
        k %= count
        if not k: return head
        tail.next = head
        tail = head
        for _ in range(count - k - 1):
            tail = tail.next
        head, tail.next = tail.next, None
        return head

Summary:

  1. 3ms, 27%
  2. nothing special.

LeetCode: 61. Rotate List