首页 > 代码库 > 【LeetCode】Rotate List

【LeetCode】Rotate List

Rotate List

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.

 

思路如下:将链表首尾相连成环。寻找尾节点的同时可以计算链表长度。

记链表长度为size,则移位次数为r=k%size。

也就是说链表的后r个节点成为新链表的前半部分,链表的前size-r个节点为新链表的后半部分。

因此head往右第size-r-1个节点为新链表的尾节点newtail,head往右第size-r个节点为新链表的头节点newhead。

将newtail->next,返回newhead即可。

由于我们在计算size时已经将原链表首尾相连,因此不存在断点。

/** * 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 == NULL || head->next == NULL)            return head;        else        {            int size = 1;            ListNode* tail = head;            while(tail->next)            {                size ++;                tail = tail->next;            }            //tail point to the last node            int r = k%size;            if(r == 0)                return head;            else            {                tail->next = head;                int shift = size-r-1;                while(shift--)                    head = head->next;                //head is new tail                ListNode* newhead = head->next;                head->next = NULL;                return newhead;            }        }    }};

【LeetCode】Rotate List