lintcode-旋转链表-170

给定一个链表,旋转链表,使得每个节点向右移动k个位置,其中k是一个非负数

样例

给出链表1->2->3->4->5->null和k=2

返回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;
        int len=1;
        ListNode *fast=head;
        
        while(fast->next){
            ++len;
            fast=fast->next;
        }
        
        k%=len;
        fast->next=head;
        int n=len-k-1;
        ListNode *cur=head;
        while(n--)
            cur=cur->next;
            
        head=cur->next;
        cur->next=NULL;
        return head;
    }
};



你可能感兴趣的:(lintcode-旋转链表-170)