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
.
注意:这题是rotate 就像是把链表首尾相连,然后向右翻转,所以存在k > length的情况,大于的时候翻转位置相当于是k % length的位置。k % length == length的情况不需要翻转。设两个指针,一个比另一个先走k % length步,然后一起往下走,使得一个走到头的时候,另一个正好走到翻转位置的前一个位置(必须指向前一个位置,因为需要将前一个位置的next置为0)。
Source
/**
* 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(head == null || head.next == null) return head;
ListNode p = head, q = head;
int i, len = 0;
while(p != null){
p = p.next;
len ++;
}
if(n % len == 0) return head;
i = n % len;
p = head;
while(i > 0){
p = p.next;
i --;
}
while(p.next != null){
p = p.next;
q = q.next;
}
p = head;
head = q.next;
q.next = null; //***链表变动一定要注意末尾变null
q = head;
while(q.next != null){
q = q.next;
}
q.next = p;
return head;
}
}
Test
public static void main(String[] args){
ListNode a = new ListNode(1);
a.next = new ListNode(2);
a.next.next = new ListNode(3);
a.next.next.next = new ListNode(4);
a.next.next.next.next = new ListNode(5);
ListNode b = new Solution().rotateRight(a, 1);
while(b != null){
System.out.println(b.val);
b = b.next;
}
}