|
@@ -0,0 +1,122 @@
|
|
|
+package main
|
|
|
+
|
|
|
+import "fmt"
|
|
|
+
|
|
|
+func main() {
|
|
|
+ var vals []int
|
|
|
+ var k int
|
|
|
+
|
|
|
+ //vals = []int{1, 2, 3, 4, 5}
|
|
|
+ //k = 8
|
|
|
+ //printList(rotateRight(createList(vals), k))
|
|
|
+ //return
|
|
|
+
|
|
|
+ vals = []int{}
|
|
|
+ k = 1
|
|
|
+ printList(rotateRight(createList(vals), k))
|
|
|
+
|
|
|
+ vals = []int{1}
|
|
|
+ k = 1
|
|
|
+ printList(rotateRight(createList(vals), k))
|
|
|
+
|
|
|
+ vals = []int{1}
|
|
|
+ k = 2
|
|
|
+ printList(rotateRight(createList(vals), k))
|
|
|
+
|
|
|
+ vals = []int{1, 2, 3, 4, 5}
|
|
|
+ k = 1
|
|
|
+ printList(rotateRight(createList(vals), k))
|
|
|
+
|
|
|
+ vals = []int{1, 2, 3, 4, 5}
|
|
|
+ k = 2
|
|
|
+ printList(rotateRight(createList(vals), k))
|
|
|
+
|
|
|
+ vals = []int{1, 2, 3, 4, 5}
|
|
|
+ k = 3
|
|
|
+ printList(rotateRight(createList(vals), k))
|
|
|
+
|
|
|
+ vals = []int{1, 2, 3, 4, 5}
|
|
|
+ k = 4
|
|
|
+ printList(rotateRight(createList(vals), k))
|
|
|
+
|
|
|
+ vals = []int{1, 2, 3, 4, 5}
|
|
|
+ k = 5
|
|
|
+ printList(rotateRight(createList(vals), k))
|
|
|
+
|
|
|
+ vals = []int{1, 2, 3, 4, 5}
|
|
|
+ k = 6
|
|
|
+ printList(rotateRight(createList(vals), k))
|
|
|
+
|
|
|
+ vals = []int{1, 2, 3, 4, 5}
|
|
|
+ k = 7
|
|
|
+ printList(rotateRight(createList(vals), k))
|
|
|
+
|
|
|
+ vals = []int{1, 2, 3, 4, 5}
|
|
|
+ k = 8
|
|
|
+ printList(rotateRight(createList(vals), k))
|
|
|
+}
|
|
|
+
|
|
|
+//Definition for singly-linked list.
|
|
|
+type ListNode struct {
|
|
|
+ Val int
|
|
|
+ Next *ListNode
|
|
|
+}
|
|
|
+
|
|
|
+func createList(vals []int) *ListNode {
|
|
|
+ var head, list *ListNode
|
|
|
+ for _, v := range vals {
|
|
|
+ if head == nil {
|
|
|
+ list = &ListNode{Val: v, Next: nil}
|
|
|
+ head = list
|
|
|
+ continue
|
|
|
+ }
|
|
|
+ var temp = &ListNode{Val: v, Next: nil}
|
|
|
+ list.Next = temp
|
|
|
+ list = list.Next
|
|
|
+ }
|
|
|
+ return head
|
|
|
+}
|
|
|
+
|
|
|
+func printList(node *ListNode) {
|
|
|
+ var temp = node
|
|
|
+ for temp != nil {
|
|
|
+ fmt.Printf("%d", temp.Val)
|
|
|
+ if temp.Next != nil {
|
|
|
+ fmt.Printf("%s", "->")
|
|
|
+ }
|
|
|
+ temp = temp.Next
|
|
|
+ }
|
|
|
+ fmt.Println()
|
|
|
+}
|
|
|
+
|
|
|
+func rotateRight(head *ListNode, k int) *ListNode {
|
|
|
+ if k == 0 {
|
|
|
+ return head
|
|
|
+ }
|
|
|
+ var length = 0
|
|
|
+ var cursor = head
|
|
|
+ for cursor != nil {
|
|
|
+ cursor = cursor.Next
|
|
|
+ length++
|
|
|
+ }
|
|
|
+
|
|
|
+ if length == 0 || k%length == 0 {
|
|
|
+ return head
|
|
|
+ }
|
|
|
+
|
|
|
+ var pos = length - k%length
|
|
|
+ var newHead *ListNode
|
|
|
+ cursor = head
|
|
|
+ for i := 1; i < pos; i++ {
|
|
|
+ cursor = cursor.Next
|
|
|
+ }
|
|
|
+
|
|
|
+ newHead = cursor.Next
|
|
|
+ cursor.Next = nil
|
|
|
+ cursor = newHead
|
|
|
+ for cursor.Next != nil {
|
|
|
+ cursor = cursor.Next
|
|
|
+ }
|
|
|
+ cursor.Next = head
|
|
|
+ return newHead
|
|
|
+}
|