首页 > 学院 > 开发设计 > 正文

LeetCode 61. Rotate List

2019-11-08 02:15:20
字体:
来源:转载
供稿:网友

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;    }};


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表