rotateRight- rotate linked list

Title

Give you the head node head of a linked list, rotate the linked list, and move each node of the linked list k positions 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]

prompt:

The number of nodes in the linked list is in the range [0, 500]
-100 <= Node.val <= 100
0 <= k <= 2 * 109

Problem-solving ideas

We turn the singly linked list into a circular linked list, and then just find the breakpoint to disconnect
Insert picture description here

Code demo

class Solution {
    
    
    public ListNode rotateRight(ListNode head, int k) {
    
    
        if(head==null)
            return head;
        int num=1;
        ListNode end=head;
        while (end.next!=null)
        {
    
    
            num++;
            end=end.next;
        }
        end.next=head;
        int pre=num-k%num;
        num=0;
        while (num!=pre-1)
        {
    
    
            head=head.next;
            num++;
        }
        ListNode res=head.next;
        head.next=null;
        return res;

    }
}

Effect demonstration

The info
answer was successful:
execution time: 1 ms, defeating 51.22% of Java users
Memory consumption: 37.9 MB, defeating 36.97% of Java users

Guess you like

Origin blog.csdn.net/tangshuai96/article/details/115262514