JL BLOG CS Lover

61. Rotate List

2018-05-02
JiefanLee

阅读:


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

Input: 1->2->3->4->5->NULL, k = 2 Output: 4->5->1->2->3->NULL Explanation: rotate 1 steps to the right: 5->1->2->3->4->NULL rotate 2 steps to the right: 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)
            return head;
        ListNode* tail=head;
        int size=1;
        //get the size of the ListNode
        while(tail->next)
        {
            tail=tail->next;
            ++size;
        }
        tail->next=head;//circle the ListNode
        k%=size;//in order to avoid the repeated conduction
        //get the position to break the circle
        for(int i=0;i<size-k;++i)
        {
            tail=tail->next;
        }
        ListNode* ans=tail->next;
        //break the circle
        tail->next=NULL;
        return ans;
    }
};

Similar Posts

Comments