Rotate List (C++)

Question:

 

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.

 

/**
 * 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 NULL;
        if(k<=0) return head;
        if(!head->next) return head;
        
        ListNode *dh = new ListNode(0);
        dh->next = head;
        
        ListNode *pre = dh, *fur = head;
        
        for(;k>1;k--) {
            if(!fur->next) fur = dh->next;
            else fur=fur->next;
        } 
        
        if(!fur->next) {
            delete dh;
            return head;
        }
        
        for(;fur->next;) {
            pre=pre->next;
            fur=fur->next;
        }
        
        fur->next = dh->next;
        dh->next = pre->next;
        pre->next = NULL;
        
        ListNode *ret = dh->next;
        delete dh;
        return ret;
    }
};

 

 欢迎关注微信公众号——计算机视觉 

 

你可能感兴趣的:(list)