标签:list bsp tps ret tno node which get question
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.
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; }
标签:list bsp tps ret tno node which get question
原文地址:http://www.cnblogs.com/linxiong/p/6822762.html