首页 > 代码库 > [leetcode]Rotate List
[leetcode]Rotate List
Rotate List
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given1->2->3->4->5->NULL
and k =2
,
return4->5->1->2->3->NULL
.
算法思路:
注意处理边界情况,k > length,需要取余的,坑爹。k == 0 || length时,不作处理
1 public class Solution { 2 public ListNode rotateRight(ListNode head, int n) { 3 ListNode hhead = new ListNode(0); 4 hhead.next = head; 5 ListNode tail = hhead; 6 int length = 0; 7 while(tail.next != null){ 8 length++; 9 tail = tail.next;10 }11 if(length == 0 || n == 0) return head;12 if(n >= length) n %= length;13 ListNode pre = hhead;14 for(int i = 0; i < length - n; pre = pre.next,i++);15 tail.next = hhead.next;16 hhead.next = pre.next;17 pre.next = null;18 return hhead.next;19 }20 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。