【LeetCode】61. 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.

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

记链表长度为n,则实际移位次数为k=k%n。记len=n-k。

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

因此head往右第len的节点为新链表的尾,第len+1为新链表的头

两端相连即可,尾部下一个设为NULL即可。

/**
 * 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)
            return head;
            
        ListNode* tail = head;
        int n = 1;
        while(tail->next != NULL)
        {
            n ++;
            tail = tail->next;
        }
        k %= n;
        if(k == 0)
            return head;
            
        int len = n-k;
        ListNode* cur = head;
        while(--len)
        {
            cur = cur->next;
        }
        ListNode* post = cur->next;
        cur->next = NULL;
        tail->next = head;
        return post;
    }
};

原文地址:https://www.cnblogs.com/ganganloveu/p/4155421.html