61. Rotate List

来源:互联网 发布:qq活动抽奖软件 编辑:程序博客网 时间:2024/06/04 19:52

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.

class Solution {public:    ListNode* rotateRight(ListNode* head, int k) {        if(!head) return head;        int len = 1;        ListNode *newH = head, *tail = head;        while(tail->next){            len++;            tail = tail->next;        }        tail->next = head ;    //****cricle the link        if(k %= len){            while(len-k){                tail = tail->next;                k++;            }        }        newH = tail->next;        tail->next = NULL;        return newH;    }};
0 0
原创粉丝点击