LeetCode力扣之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.

package leetCode;

/**
 * Created by lxw, [email protected] on 2018/3/10.
 */
class ListNode{
    int val;
    ListNode next;
    ListNode(int x){
        val = x;
    }
}

public class L061_Rotate_List {

    public ListNode rotateRight(ListNode head, int k){

        if (head == null || head.next == null){
            return head;
        }
        int len = 1;
        ListNode tail = head;
        while (tail.next != null){
            len ++;
            tail = tail.next;
        }
        tail.next = head;
        k %= len;

        for (int i = 1; i < len - k; i ++){
            head = head.next;
        }

        try {
            return head.next;
        } finally {
            head.next = null;
        }
    }

    public static void main(String[] args){
        L061_Rotate_List tmp = new L061_Rotate_List();
        ListNode head = new ListNode(1);
        ListNode tmpNode = head;
        for (int i =2; i <= 5; i++){
            ListNode cur = new ListNode(i);
            tmpNode.next = cur;
            tmpNode = cur;
        }
        tmpNode.next = null;

        head = tmp.rotateRight(head, 2);
        while (head != null){
            System.out.print(head.val + "->");
            head = head.next;
        }
        System.out.print("NULL.");

    }
}

你可能感兴趣的:(算法面试)