Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit af17dd7

Browse files
committed
kit 添加了 ListNode 的两个处理函数。
1 parent 4c6b311 commit af17dd7

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

kit/ListNode.go

+21
Original file line numberDiff line numberDiff line change
@@ -55,3 +55,24 @@ func (l *ListNode) GetNodeWith(val int) *ListNode {
5555
}
5656
return res
5757
}
58+
59+
// Ints2ListWithCycle returns a list whose tail point to pos-indexed node
60+
// head's index is 0
61+
// if pos = -1, no cycle
62+
func Ints2ListWithCycle(nums []int, pos int) *ListNode {
63+
head := Ints2List(nums)
64+
if pos == -1 {
65+
return head
66+
}
67+
c := head
68+
for pos > 0 {
69+
c = c.Next
70+
pos--
71+
}
72+
tail := c
73+
for tail.Next != nil {
74+
tail = tail.Next
75+
}
76+
tail.Next = c
77+
return head
78+
}

kit/ListNode_test.go

+10
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,13 @@ func Test_getNodeWith(t *testing.T) {
5656
actual := ln.GetNodeWith(val)
5757
ast.Equal(expected, actual)
5858
}
59+
60+
func Test_Ints2ListWithCycle(t *testing.T) {
61+
ast := assert.New(t)
62+
ints := []int{1, 2, 3}
63+
l := Ints2ListWithCycle(ints, -1)
64+
ast.Equal(ints, List2Ints(l))
65+
66+
l = Ints2ListWithCycle(ints, 1)
67+
ast.Panics(func() { List2Ints(l) })
68+
}

0 commit comments

Comments
 (0)