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,
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
分析:
将链表后面一部分移动到前面,思路是先连成环,再在合适的地方断开。
这里k有可能超过链表长度,因此要有个取余操作。
/**
* 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) {
//这里有个问题,就是k有可能大于链表长度
if(head == null || head.next == null)
return head;
ListNode point = head;
int len = 1;
while(point.next != null){
point = point.next;
len++;
}
point.next = head;//连成环
int count = len - n%len;
while(count > 0){
point = point.next;
count--;
}
head = point.next;//断开环
point.next = null;
return head;
}
}