首页 > 其他 > 详细

LeetCode - Rotate List

时间:2015-12-27 17:47:55      阅读:117      评论: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.

思路:

此题和Remove Nth Node from End of List类似,但首先得统计总的个数

package list;

public class RotateList {

    public ListNode rotateRight(ListNode head, int k) {
        if (k == 0 || head == null) return head;
        
        ListNode x = head;
        int count = 0;
        while (x != null) {
            ++count;
            x = x.next;
        }
        
        int n = k;
        if (k >= count) {
            if (k % count == 0)
                return head;
            else
                n = k % count;
        }
            
        ListNode p = head;
        ListNode q = head;
        while (p != null && n > 0) {
            p = p.next;
            --n;
        }
        
        while (p.next != null && q.next != null) {
            p = p.next;
            q = q.next;
        }
        
        ListNode newhead = q.next;
        p.next = head;
        q.next = null;
        return newhead;
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        RotateList r = new RotateList();
        ListNode a1 = new ListNode(1);
        ListNode a2 = new ListNode(2);
        ListNode a3 = new ListNode(3);
        ListNode a4 = new ListNode(4);
        ListNode a5 = new ListNode(5);
        a1.next = a2;
        a2.next = a3;
        a3.next = a4;
        a4.next = a5;
        a5.next = null;
        ListNode head = r.rotateRight(a1, 2);
        while (head != null) {
            System.out.println(head.val);
            head = head.next;
        }
    }

}

 

LeetCode - Rotate List

原文:http://www.cnblogs.com/shuaiwhu/p/5080438.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!