Leetcode beginner - rotating list

topic:

analysis:

To 1-> 2-> 3-> 4-> 5 k = 2 Example

The chain is connected end to end

The head and end positions are sequentially set back nk original chain length n

It should be shifted in position 3

Then the end of next changed to null

This question is even completed

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        ListNode end=head;
        //当链表为空时,直接返回
        if(head==null) return head;
        int n=1;
        while(end.next!=null){
            n++;
            end=end.next;
        }
        k=k%n;
        //当k的余数为0时,链表不需要移动,直接返回head
        if(k==0)return head;
        end.next=head;
        for(int i=0;i<n-k;i++){
            head=head.next;
            end=end.next;
        }
        end.next=null;
        return head;
    }
}

result:

Published 57 original articles · won praise 3 · Views 1052

Guess you like

Origin blog.csdn.net/qq_39377543/article/details/104267746