File tree 2 files changed +123
-0
lines changed
2 files changed +123
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * @lc app=leetcode.cn id=61 lang=golang
3
+ * @lcpr version=30204
4
+ *
5
+ * [61] 旋转链表
6
+ */
7
+ package main
8
+
9
+ import "container/list"
10
+
11
+ type ListNode struct {
12
+ Val int
13
+ Next * ListNode
14
+ }
15
+
16
+ // @lcpr-template-start
17
+
18
+ // @lcpr-template-end
19
+ // @lc code=start
20
+ /**
21
+ * Definition for singly-linked list.
22
+ * type ListNode struct {
23
+ * Val int
24
+ * Next *ListNode
25
+ * }
26
+ */
27
+ func rotateRight (head * ListNode , k int ) * ListNode {
28
+ if head == nil || head .Next == nil {
29
+ return head
30
+ }
31
+ l := list .New ()
32
+ num := 0
33
+ for p := head ; p != nil ; p = p .Next {
34
+ l .PushBack (p .Val )
35
+ num ++
36
+ }
37
+ if k > num {
38
+ k = k % num
39
+ }
40
+ for i := 0 ; i < k ; i ++ {
41
+ v := l .Remove (l .Back ())
42
+ l .PushFront (v )
43
+ }
44
+ for p , pl := head , l .Front (); p != nil ; p = p .Next {
45
+ p .Val = pl .Value .(int )
46
+ pl = pl .Next ()
47
+ }
48
+ return head
49
+ }
50
+
51
+ // / 先组成环链,再从尾部移动num-k%num步,断开环链
52
+ func rotateRightRing (head * ListNode , k int ) * ListNode {
53
+ if head == nil || head .Next == nil || k == 0 {
54
+ return head
55
+ }
56
+ n , p := 1 , head
57
+ for p .Next != nil {
58
+ p = p .Next
59
+ n ++
60
+ }
61
+ p .Next = head // 组成环链
62
+ k %= n
63
+ for i := 1 ; i <= n - k ; i ++ {
64
+ p = p .Next
65
+ }
66
+ head , p .Next = p .Next , nil
67
+ return head
68
+ }
69
+
70
+ // @lc code=end
71
+
72
+ /*
73
+ // @lcpr case=start
74
+ // [1,2,3,4,5]\n2\n
75
+ // @lcpr case=end
76
+
77
+ // @lcpr case=start
78
+ // [0,1,2]\n4\n
79
+ // @lcpr case=end
80
+
81
+ */
Original file line number Diff line number Diff line change
1
+ package main
2
+
3
+ import (
4
+ "fmt"
5
+ "testing"
6
+ )
7
+
8
+ func Array2LinkedList (arr []int ) * ListNode {
9
+ if len (arr ) == 0 {
10
+ return nil
11
+ }
12
+
13
+ // 创建头节点
14
+ head := & ListNode {Val : arr [0 ]}
15
+ current := head
16
+
17
+ // 遍历数组,逐个创建节点并连接
18
+ for i := 1 ; i < len (arr ); i ++ {
19
+ current .Next = & ListNode {Val : arr [i ]}
20
+ current = current .Next
21
+ }
22
+
23
+ return head
24
+ }
25
+
26
+ // 打印链表
27
+ func PrintLinkedList (head * ListNode ) {
28
+ for head != nil {
29
+ fmt .Print (head .Val , " -> " )
30
+ head = head .Next
31
+ }
32
+ fmt .Println ("nil" )
33
+ }
34
+
35
+ func Test61 (t * testing.T ) {
36
+ head := Array2LinkedList ([]int {2 , 3 , 4 , 5 })
37
+ PrintLinkedList (head )
38
+
39
+ PrintLinkedList (rotateRight (head , 5 ))
40
+ head = Array2LinkedList ([]int {2 , 3 , 4 , 5 })
41
+ PrintLinkedList (rotateRight (head , 2 ))
42
+ }
You can’t perform that action at this time.
0 commit comments