LeetCode 61. Rotate List

来源:互联网 发布:php进销存管理系统 编辑:程序博客网 时间:2024/03/29 15:41

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.

answer:

class Solution {public:    ListNode* rotateRight(ListNode* head, int k) {        if(k == 0 ) return head;        ListNode * pre = head, * end = head;        if(end == NULL || end->next == NULL) return head;        int length = 1;        while(k > 0){            while(end->next != NULL){                pre = end;                end = end->next;                length ++;            }            cout << length;            if(k > length) k = k % length;            if(k != 0){                end->next = head;                pre->next = NULL;                head = end;            }                        k --;                    }        return head;    }};


0 0
原创粉丝点击