Wednesday, February 21, 2018

Rotate List

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.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if (head == NULL || k < 1) {
            return head;
        }
        ListNode *prev_head = head, *trav = head, *prev = NULL;
       
        int length = 0;
        while (trav != NULL) {
            length++;
            trav = trav -> next;
        }
        trav = head;
        k = length - (k % length);
       
        while (k > 0) {
            if (trav != NULL) {
                prev = trav;
                trav = trav -> next;
                k--;
            } else {
                trav = head;
            }
        }
        if (trav == NULL || prev == NULL) {
            return head;
        }
        head = trav;
        prev -> next = NULL;
       
        while (trav -> next != NULL) {
            trav = trav -> next;
        }
        trav -> next = prev_head;
        return head;
    }
};

No comments:

Post a Comment