Rotate List

题目大意

给出一个单链表,和一个K值,根据K值往右旋转,例如:

思路

先求出链表的长度size,其实按着倒数第K%size个位置旋转,这个位置即size-(K%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 || k < 0)
            return NULL;
        ListNode *tmp = head;
        int size = 0;
        while(tmp != NULL)
            {
                tmp = tmp->next;
                ++size;
            }
        k = size - (k % size);
        if(k == size)
            return head;
        k = k - 1;
        ListNode *rev = NULL;
        ListNode *pre = head;
        ListNode *token = head;
        ListNode *cur = head;
        int index = 0;
        while(index <= k && cur != NULL)
        {
            pre = cur;
            cur = cur->next;
            ++index;
        }
        rev = cur;
        if(cur == NULL)
            return head;
        while(cur->next != NULL)
            cur = cur->next;
        cur->next = token;
        pre->next = NULL;
        return rev;
    }
};

注意

两段链表接在一起的时候,注意原来前半部分最后一个指针应当赋值为NULL

原文地址:https://www.cnblogs.com/kaituorensheng/p/3647668.html