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

Leetcode 61 -- Rotate List

时间:2017-05-08 00:26:33      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:list   bsp   tps   ret   tno   node   which   get   question   

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.

Subscribe to see which companies asked this question.

 
Note: 注意K可能很大,可能会超时。
 
public ListNode rotateRight(ListNode head, int k) {
        if (head == null) {
            return null;
        }
        
        ListNode before = head;
        ListNode after = head;
        
        // get length 
        int length = 0;
        while(after != null) {
            length++;
            after = after.next;
        }
    
        // get valid k less than length
        k = k % length;
        
        after = head;
        for(int i=0; i<k; i++) {
            after = after.next;
        }
        
        while (after.next != null) {
            before = before.next;
            after = after.next;
        }
        
        after.next = head;
        head = before.next;
        before.next = null;
        return head;
    }

 

Leetcode 61 -- Rotate List

标签:list   bsp   tps   ret   tno   node   which   get   question   

原文地址:http://www.cnblogs.com/linxiong/p/6822762.html

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