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;
    }
}

 

posted @ 2016-06-02 08:43  茜茜的技术空间  阅读(203)  评论(0编辑  收藏  举报