首页 > 编程语言 > 详细

Java for LeetCode 061 Rotate List

时间:2015-05-15 22:44:37      阅读:281      评论: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.

解题思路:

只需找到对应的位置,然后指向head,接着把之前节点指向null即可,注意k可以取大于length的值,所以k%=length,JAVA实现如下:

    public ListNode rotateRight(ListNode head, int k) {
    	if(head==null||head.next==null)
    		return head;
    	ListNode temp=head;
    	int length=1;
    	while(temp.next!=null){
    		temp=temp.next;
    		length++;
    	}
    	if(k==length)
    		return head;
    	temp.next=head;
    	temp=head;
    	for(int i=1;i<length-k;i++)
    		temp=temp.next;
    	head=temp.next;
    	temp.next=null;
        return head;
    }

 

Java for LeetCode 061 Rotate List

原文:http://www.cnblogs.com/tonyluis/p/4506869.html

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