当前位置:网站首页>LeetCode-61

LeetCode-61

2022-07-05 06:16:00 GreedySnaker

Give you a list of the head node head , Rotate the list , Move each node of the list to the right k A place .
 Insert picture description here

At first, I thought about finding a new head according to the number of moves , New tail , Direct link . Later, we found that the circular linked list can record the node precursor and follower with fewer variables .

class Solution {
    
public:
    ListNode* rotateRight(ListNode* head, int k) 
    {
    
        // Does not meet the conditions or there is only one node 
        if (head == NULL || head->next == NULL || k == 0)
        {
    
            return head;
        }
        
        // Record the number of linked list elements , Find the tail node  
        ListNode* temp = head;
        int num = 1;
        while (temp->next != NULL) 
        {
    
            temp = temp->next;
            num++; 
        }

        //k When it is greater than the number of elements , Just deal with the remainder 
        k = k % num;
        if (k == 0)
        {
    
            return head;
        }

        // Connect the single linked list into a circular list 
        temp->next = head;
 
        // According to the number of shifts to the right , Cut off the ring linked list at the corresponding position , Return to new header 
        temp = head;
        for (int i = 1; i < (num - k); i++)
        {
    
            temp = temp->next;
        }
        ListNode* res = temp->next; 
        // Segmented ring linked list 
        temp->next = NULL; 
        return res;
    }
};

原网站

版权声明
本文为[GreedySnaker]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140618227012.html