-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path61.java
More file actions
79 lines (76 loc) · 1.94 KB
/
61.java
File metadata and controls
79 lines (76 loc) · 1.94 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
__________________________________________________________________________________________________
sample 0 ms submission
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null) return null;
ListNode start = head;
int count = 1;
while(start.next != null) {
start = start.next;
count++;
}
start.next = head;
for(int i = count - k % count - 1; i > 0; i--) {
head = head.next;
}
start = head.next;
head.next = null;
return start;
}
}
__________________________________________________________________________________________________
sample 35348 kb submission
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head==null||k==0) return head;
int len = 0;
ListNode p = head;
for(int i = 0;i < k; ++i){
if(p!=null){
++len;
p = p.next;
}else{
break;
}
}
if(len==k&&p==null){
return head;
}
if(len<k){
k %= len;
if(k==0){
return head;
}
p = head;
for(int i = 0;i < k; ++i){
p = p.next;
}
}
ListNode b = head;
while(p.next!=null){
p = p.next;
b = b.next;
}
p.next = head;
ListNode r = b.next;
b.next = null;
return r;
}
}
__________________________________________________________________________________________________