-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotate List
More file actions
42 lines (42 loc) · 776 Bytes
/
Rotate List
File metadata and controls
42 lines (42 loc) · 776 Bytes
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
/**
* 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 head1 = head;
ListNode head2 = head;
ListNode end1 = head;
ListNode end2 = head;
for (int i = 0; i < n; i++) {
end2 = end2.next;
if (end2 == null) {
end2 = head;
}
}
if (end2 == null) {
return head;
}
while (end2.next != null) {
end2 = end2.next;
end1 = end1.next;
}
head2 = end1.next;
if (head2 == null) {
return head;
}
end2.next = head1;
end1.next = null;
return head2;
}
}