【Leetcode】61. Rotate List

Given a list, rotate the list to the right by k places, where k is non-negative.

Example:

Given 1->2->3->4->5->NULL and k = 2,

return 4->5->1->2->3->NULL.

Tips:右移结点,过程如下:

k=2,右移两次:

①5->1->2->3->4

②4->5->1->2->3

思路:(1)实例化一个fast指针,使其等于head结点,使fast指针先向后移动k次。

(2)创建一个slow指针,然后两个指针一起向后移动,直到fast.next!=null,停止。

(3)k的值可能大于链表总长度,需要对k取余,k = k%count;

(4)使fast.next等于head,slow的下一个结点作为新的头结点。

package medium;

import dataStructure.ListNode;

public class L61RotateList {
    /*
     * Given a list, rotate the list to the right by k places, where k is
     * non-negative.
     * 
     * Example:
     * 
     * Given 1->2->3->4->5->NULL and k = 2,
     * 
     * return 4->5->1->2->3->NULL.
     * 
     */
    public ListNode rotateRight(ListNode head, int k) {
        if(head==null || k<0)return null;
        ListNode node = new ListNode(0);
        node.next = head;
        ListNode fast=head;
        ListNode newHead=head;
        int count=0;
        while(newHead!=null){
            count++;
            newHead=newHead.next;
        }
        if(k > count)
               k = k%count;
        
        for(int i=0;i<k;i++){
            fast=fast.next;
        }
        if(fast==null){
            return node.next;
        }else{
            ListNode slow=head;
            while(fast.next!=null){
                slow=slow.next;
                fast=fast.next;
            }
            fast.next=head;
            ListNode cur=slow.next;
            node.next=cur;
            slow.next=null;
        }
        return node.next;
    }

    public static void main(String[] args) {
        ListNode head1 = new ListNode(1);
        ListNode head2 = new ListNode(2);
        ListNode head3 = new ListNode(3);
        ListNode head4 = new ListNode(4);
        ListNode head5 = new ListNode(5);
        ListNode head6 =  null;
        head1.next = head2;
        head2.next = head3;
        head3.next = head4;
        head4.next = head5;
        head5.next = head6;
        L61RotateList l61=new L61RotateList();
        int k=2;
        ListNode node=l61.rotateRight(head1, k);
        while(node!=null){
            System.out.println(node.val);
            node=node.next;
        }
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~");
        ListNode h1 = new ListNode(1);
        ListNode h2=new ListNode(2);
        h1.next=h2;
        h2.next=null;
        ListNode node1=l61.rotateRight(h1, 3);
        while(node1!=null){
            System.out.println(node1.val);
            node1=node1.next;
        }
    }
}
原文地址:https://www.cnblogs.com/yumiaomiao/p/8448467.html