LeetCode题解:Rotate List

Rotate List

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

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

思路:

这个题目的陷阱中,输入为空指针大约不算其中之一。主要的问题是k可以大于这个链表的总长度。这样,真正的旋转次数是k % length(ListNode)。那么新的head就是length(ListNode) - k  + 1的结点。

题解:

 

/**
 * 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 == nullptr)
            return nullptr;
        
        // first update the length of the list
        ListNode* len_iter = head;
        int len = 1;
        while(len_iter->next != nullptr)
            ++len, len_iter = len_iter->next;

        k = k % len;
        
        if (k == 0)
            return head;
            
        len_iter->next = head;  // make it a circled link list
        ListNode* breakpoint = head;
        for(int i = 0; i < len - k - 1; ++i)
            breakpoint = breakpoint->next;
        
        head = breakpoint->next;
        breakpoint->next = nullptr;
        
        return head;
    }
};


 


 

你可能感兴趣的:(LeetCode)