61. Rotate List

题目:

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

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

链接:http://leetcode.com/problems/rotate-list/

题解:

先遍历一次链表,将尾部和头部相连,再进行移动。注意右移k步相当于prehead travel len - k步。

Time Complexity - O(n), Space Complexity - O(1)

public class Solution {

    public ListNode rotateRight(ListNode head, int k) {

        if(head == null || k == 0)

            return head;

        ListNode node = head;

        int len = 1;

        while(node.next != null){

            node = node.next;

            len ++;

        }

        node.next = head;

        k %= len;

        for(int i = 0; i < len - k; i++)

            node = node.next;

        

        head = node.next;

        node.next = null;

        return head;

    }

}

 

 

测试:

你可能感兴趣的:(list)