forked from dylansun/leetcode-cn-scala
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNo61.scala
43 lines (40 loc) · 1.18 KB
/
No61.scala
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
/**
* Created by lilisun on 2/23/19.
*/
object No61 {
def rotateRight(head: ListNode, k: Int): ListNode = if (k == 0 || head == null || head.next == null) head else {
var len = 1
@annotation.tailrec
def findKthNode(head: ListNode, k: Int): (Int, ListNode) =
if (head.next == null || k == 0) (k, head)
else {
len += 1
findKthNode(head.next, k - 1)
}
@annotation.tailrec
def loop(front: ListNode, back: ListNode): (ListNode, ListNode) =
if (front.next == null) (front, back)
else loop(front.next, back.next)
val (remaining, node) = findKthNode(head, k)
if (remaining == 1) { // k is less than or equal to length of list
if (node.next == null) head
else {
val (front, back) = loop(node, head)
val result = back.next
back.next = null
front.next = head
result
}
} else if (k % len == 0) head else { // k is greater than length of list
val offset = k % len
var t = head
for (_ <- 0 until offset)
t = t.next
val (front, back) = loop(t, head)
val result = back.next
back.next = null
front.next = head
result
}
}
}