lintcode-旋转链表-170

来源:互联网 发布:hadoop python api 编辑:程序博客网 时间:2024/06/02 02:20

给定一个链表,旋转链表,使得每个节点向右移动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;    }};



0 0