Leetcode 61 -- Rotate List
Posted linxiong1991
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 61 -- Rotate List相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章