-
Notifications
You must be signed in to change notification settings - Fork 0
/
RotateList.java
48 lines (41 loc) · 1.04 KB
/
RotateList.java
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
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* 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 || n == 0)
return head;
//get the length and tail of the list
int length = 1;
ListNode temp = head;
while(temp.next != null){
length++;
temp = temp.next;
}
ListNode tail = temp;
if(n % length == 0)
return head;
else
n = n % length;
//get the pointer before new head
int i = length - n - 1;
temp = head;
while(i > 0){
temp = temp.next;
i--;
}
//move last n nodes to the head of list
ListNode newHead = temp.next;
temp.next = null;
tail.next = head;
return newHead;
}
}