[leetcode] 61. Rotate List

来源:互联网 发布:霍先生家的安之知书包 编辑:程序博客网 时间:2024/04/29 06:10

Given a list, rotate the list to the right byk places, where k is non-negative.

For example:

Given1->2->3->4->5->NULL andk =2,

return
return4->5->1->2->3->NULL.

这道题是循环右移链表,题目难度为Medium。

要循环右移链表,需要找出新的链表头位置,然后将表尾和表头相接,同时将新表尾的next指针置为NULL。找新链表头位置的方法相信大家都知道,就不再详述。k值可能比较大,这样在遍历一遍链表之后获取链表长度,此时计数可能还比k小很多,这样用k取余链表长度得到真正需要右移的次数。这样再按照上面的方法即可完成右移。具体代码:

class Solution {public:    ListNode* rotateRight(ListNode* head, int k) {        if(!head || !k) return head;        ListNode* fast = head;        ListNode* slow = head;        ListNode* newHead = NULL;        int cnt = 0;        while(fast && cnt<k) {            fast = fast->next;            cnt++;        }        if(!fast) {            k %= cnt;            cnt = 0;            fast = head;            while(fast && cnt<k) {                fast = fast->next;                cnt++;            }        }        while(fast) {            if(!fast->next) {                ListNode* tmp = slow;                fast->next = head;                newHead = slow->next;                tmp->next = NULL;                break;            }            fast = fast->next;            slow = slow->next;        }        return newHead;    }};
看到有人的代码先把链表首尾相接然后右移,这样代码看起来确实简单很多,不过在k较小时会多遍历一遍链表,所以就不给大家推荐了。

0 0
原创粉丝点击