forked from franklingu/leetcode-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
46 lines (45 loc) · 1.12 KB
/
Copy pathSolution.java
File metadata and controls
46 lines (45 loc) · 1.12 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
/**
* Given a list, rotate the list to the right by k places, where k is non-negative.
*
* For example:
* Given 1->2->3->4->5->NULL and k = 2,
* return 4->5->1->2->3->NULL.
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int k) {
ListNode faster = head;
ListNode slower = head;
if (head == null) {
return head;
}
int lengthOfList = 0;
while (faster != null) {
lengthOfList++;
faster = faster.next;
}
faster = head;
k = k % lengthOfList;
for (int i = 0; i < k && faster != null; i++) {
faster = faster.next;
}
if (faster == null || k == 0) {
return head;
}
while (faster.next != null) {
slower = slower.next;
faster = faster.next;
}
ListNode newHead = slower.next;
slower.next = null;
faster.next = head;
return newHead;
}
}