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

[leetcode] Rotate List

时间:2014-06-27 11:39:33      阅读:289      评论:0      收藏:0      [点我收藏+]

标签:class   code   java   http   tar   ext   

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

For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.

https://oj.leetcode.com/problems/rotate-list/

思路1:先遍历一遍求长度,然后从头再开始走k%len步,设置新的头尾节点,连接原来的头尾节点。

思路2:遍历求长度,将首尾连接,继续走到新的头尾,断开。

 

思路1代码:

public class Solution {
    public ListNode rotateRight(ListNode head, int n) {
        if (head == null)
            return null;
        int len = 0;
        ListNode p = head;
        while (p != null) {
            len++;
            p = p.next;
        }
        
        p = head;
        int i;
        n = n % len;
        if (n == 0)
            return head;
        for (i = 0; i < len - n - 1; i++)
            p = p.next;
        ListNode newTail = p;
        ListNode newHead = p.next;

        while (p.next != null)
            p = p.next;
        p.next = head;
        newTail.next = null;
        return newHead;

    }

    public static void main(String[] args) {
        ListNode head = ListUtils.makeList(1, 2, 3, 4, 5);
        ListUtils.printList(head);
        head = new Solution().rotateRight(head, 2);
        ListUtils.printList(head);
    }
}

 

 

[leetcode] Rotate List,布布扣,bubuko.com

[leetcode] Rotate List

标签:class   code   java   http   tar   ext   

原文地址:http://www.cnblogs.com/jdflyfly/p/3810773.html

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