[LeetCode Brush Questions] 61. Rotating Linked List

Give you the head node of a linked list  head , rotate the linked list, and move each node of the linked list k one position to the right  .

Example 1:

Input: head = [1,2,3,4,5], k = 2

Output: [4,5,1,2,3]

Example 2:

Input: head = [0,1,2], k = 4

Output: [2,0,1]

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(head==NULL||k==0)
        {
            return head;
        }
        //1、计数节点,并把链表形成一个环
        int sum = 1;
        ListNode* temp = head;
        while(temp->next!=NULL)
        {
            sum++;
            temp=temp->next;
        }
        temp->next = head;
        //2、从原始的头结点开始计数,找到k-1位置时,断链
        int count = 0;
        k = k % sum;
        while(count < sum - k-1)
        {
            head = head->next;
            count++;
        }
        ListNode* newHead = head->next;
        head->next = NULL;
        return newHead;
    }
};

Reference: https://leetcode-cn.com/problems/rotate-list/

Guess you like

Origin blog.csdn.net/Zhouzi_heng/article/details/115265521