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.
1. 首先,需要先遍历一遍拿到这个list的长度,顺便把最后一个元素的next指向第一个head,做成一个循环链表。
2. 第二遍遍历,走到第length-k个元素,记录下下一个元素为要返回的元素,然后把这个元素的next设置为null。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode rotateRight(ListNode head, int n) { if(n==0||head==null){ return head; } // get length int length = 0; ListNode cursor = head; ListNode tail = null; while(cursor!=null){ length++; tail = cursor; cursor = cursor.next; } n = n%length; tail.next = head; int i=0; cursor = head; while(i<length-n){ tail = cursor; cursor = cursor.next; i++; } tail.next=null; return cursor; } }