码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 61. Rotate List

时间:2016-06-02 09:37:38      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/anne-vista/p/5551786.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!