Rotate List(旋转链表)

问题

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

Have you met this question in a real interview? Yes
Example
Given 1->2->3->4->5 and k = 2, return 4->5->1->2->3.

分析

首先算出来链表的总长度,然后可以理解,偏移量K其实就是把最后的K个长度放到前边。所以我们找到后边K个长度的前一个位置,修改指针就可以了。

代码

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


public class Solution {
    /*
     * @param head: the List
     * @param k: rotate to the right k places
     * @return: the list after rotation
     */
    public ListNode rotateRight(ListNode head, int k) {
        int n = 0;
        ListNode tail = head;
        while (tail != null) {
            n++;
            if (tail.next == null) {
                break;
            }
            tail = tail.next;
        }
        if (n < 2) {
            return head;
        }
        k = k % n;
        if (k==0){
            return head;
        }
        ListNode newHead = head;
        int temp = 1;
        while (temp < n - k) {
            newHead = newHead.next;
            temp++;
        }
        ListNode node = newHead.next;
        newHead.next = null;
        tail.next = head;
        return node;
    }
}

你可能感兴趣的:(Rotate List(旋转链表))