-
Notifications
You must be signed in to change notification settings - Fork 0
/
rotate-list.go
47 lines (42 loc) · 871 Bytes
/
rotate-list.go
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
package main
import (
"fmt"
"bytes"
)
type listNode struct {
Val int
Next *listNode
}
func (n *listNode) String() string {
var buf bytes.Buffer
for nn := n; nn != nil; nn = nn.Next {
buf.WriteString(fmt.Sprintf("[%d]", nn.Val))
}
return buf.String()
}
func rotateRight(head *listNode, k int) *listNode {
if head == nil || head.Next == nil || k <= 0 {
return head
}
slow, fast := head, head
length := 1
for ; fast.Next != nil; length++ {
fast = fast.Next
}
k = k % length
if k == 0 {
return head
}
for i := 0; i < length-k-1; i++ {
slow = slow.Next
}
newHead := slow.Next
slow.Next, fast.Next = nil, head
return newHead
}
func main() {
head := &listNode{1, &listNode{2, &listNode{3, &listNode{4, &listNode{5, nil}}}}}
head2 := &listNode{1, &listNode{2, nil}}
fmt.Println(rotateRight(head, 2))
fmt.Println(rotateRight(head2, 2))
}