-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rotate List
35 lines (35 loc) · 905 Bytes
/
Rotate List
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(head == null || n == 0)
return head;
ListNode pivot = head;
int len = 1;
while(pivot.next != null)
{
len++;
pivot = pivot.next;
}
pivot.next = head;
n = n%len; //if n>len, need to go around the loop for several times
for(int i=0; i<len-n; i++)
{
pivot = pivot.next;
}
head = pivot.next;
pivot.next = null;
return head;
}
}