Leetcode 61. Rotate List

Posted 茜茜的技术空间

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 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.


Analysis:

1. compute the length of list m
2. partition list into two small list, 注意正好移到list尾端,下一个是NULL!!
    before list is list1, after list is list2, set last node in list1 list1.next = null
3. concatenate the tail of two list to the head of one list


Java code

20160601

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        //1. compute the length of list m
        //2. partition list into two small list,
        //     before list is list1, after list is list2, set last node in list1 list1.next = null
        //3. concatenate the tail of two list to the head of one list
        
         //base case
        if(head == null || head.next == null || k == 0) {
            return head;
        }
        int m = getLength(head);
        int moveStep = m - k % m - 1;
        ListNode cur = head;
        ListNode one = head;
        ListNode two = null;
        
        while(moveStep > 0) {
            cur = cur.next;
            moveStep--;
        }
        if(cur.next == null) {  //move to the end of the linked list, no rotate
            return head;
        }
        two = cur.next;
        cur.next = null;
        ListNode twohead = two;
        while(two.next != null) {
            two = two.next;
        }
        two.next = one;
        return twohead;
    }
    
    private int getLength(ListNode head) {
        int len = 0;
        while(head != null) {
            head = head.next;
            len++;
        }
        return len;
    }
}

 

以上是关于Leetcode 61. Rotate List的主要内容,如果未能解决你的问题,请参考以下文章

一天一道LeetCode#61. Rotate List

LeetCode 61. Rotate List

Leetcode61 Rotate List

Leetcode 61 -- Rotate List

leetcode61. Rotate List

LeetCode-61-Rotate List