forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotateList.java
More file actions
22 lines (17 loc) · 613 Bytes
/
RotateList.java
File metadata and controls
22 lines (17 loc) · 613 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class RotateList {
public ListNode rotateRight(ListNode head, int n) {
if (head == null || head.next == null) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode fast = dummy, slow = dummy;
int i;
for (i = 0; fast.next != null; i++)//Get the total length
fast = fast.next;
for (int j = i - n % i; j > 0; j--) //Get the i-n%i th node
slow = slow.next;
fast.next = dummy.next; //Do the rotation
dummy.next = slow.next;
slow.next = null;
return dummy.next;
}
}