Rotate List

Description

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

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

Lintcode_ladder

Method

  1. connect the begin and end of list to a loop, then finding the new head and disconnect it
  2. x

Example

  1. 1
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    /**
     * @param head: the list
     * @param k: rotate to the right k places
     * @return: the list after rotation
     */
    ListNode *rotateRight(ListNode *head, int k) {
        // write your code here
        if (!head) {
            return nullptr;
        }
        // connect the list as a loop
        ListNode* cur = head;
        int len = 1;
        while (cur->next) {
            ++len;
            cur = cur->next;
        }
        cur->next = head;
        // find new head with k
        // make sure k: 1..< ?? 
        ListNode* newhead = nullptr;
        int index = len - k % len;
        while (index > 0) {
            --index;
            cur = cur->next;
        }
        newhead = cur->next;
        cur->next = nullptr;
        return newhead;
    }
};

Similar problems

x

Tags

x

results matching ""

    No results matching ""