将给定的链表向右转动k个位置,k是非负数。
例如:
给定1->2->3->4->5->null , k=2,
返回4->5->1->2->3->null。
/* * function ListNode(x){ * this.val = x; * this.next = null; * } */ /** * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ function rotateRight( head , k ) { if(head==null || k==0) {return head} var len = 1 var current = head while(current.next){ len++ current = current.next } var num = k%len var x = len - num current.next = head //首尾相连形成环 for(var i = 0; i < x; i++){ current = current.next } //找到新的首结点 head = current.next //将值赋值给head current.next = null //断开环 return head } module.exports = { rotateRight : rotateRight };