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
, return 4->5->1->2->3->NULL
. /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
//关键在于找到旋转节点pivot,pivot.next成为新的头,pivot成为新的尾,而原list的尾后面接上原list的头public class Solution { public ListNode rotateRight(ListNode head, int k) { if(head==null) return head; int length = 0; ListNode myNode = head; while(myNode != null){ //利用循环求得list的长度 length++; myNode = myNode.next; } if(k >= length) k = k % length; //此处注意,k是有可能大于长度的 if(length<=1 || k==0) return head; //此两种情况都不用旋转,直接返回即可 int pivot = length - 1 - k; //旋转点位置,题目示例中,pivot=2,代表list中第三个节点 ListNode newHead = null; myNode = head; //重复利用myNode for(int i=0; i