【LeetCode刷题】61. 旋转链表

给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。

示例 1:

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

输出:[4,5,1,2,3]

示例 2:

输入:head = [0,1,2], k = 4

输出:[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;
    }
};

参考:https://leetcode-cn.com/problems/rotate-list/

猜你喜欢

转载自blog.csdn.net/Zhouzi_heng/article/details/115265521