将数组转换为Golang的链接列表
链接列表的定义:
type ListNode struct {
Val int
Next *ListNode
}
插入指针操作的助手: 我知道root.val == 0不是解决输入数组包含0个元素的问题,因此请提出一种更通用的方法来解决此问题。
func insert(root *ListNode, elem int) *ListNode {
temp := ListNode{Val: elem, Next: nil}
if root.Val == 0 {
root = &temp
} else {
curr := root
for curr.Next != nil {
curr = curr.Next
}
curr = &temp
}
return root
}
主要功能:
func convertToList(arr []int) *ListNode {
var head ListNode
for _, val := range arr {
head = *insert(&head, val)
}
return &head
}
测试功能的字符串函数实现:
func (l *ListNode) String() string {
x := make([]int, 0)
curr := l
for curr != nil {
x = append(x, curr.Val)
curr = curr.Next
}
return fmt.Sprint(x)
}
我要复制输出的主要功能:
func main() {
arr := []int{1, 2, 3, 4, 5}
listNode := convertToList(arr)
fmt.Println(listNode.String())
}
输出:
[1]
预期输出:
[1 2 3 4 5]
definition of linked list:
type ListNode struct {
Val int
Next *ListNode
}
insert helper that does the pointer manipulation:
I am aware that root.Val == 0 is does not solve problems where the input array contains 0 elements, so please suggest a more general approach to solve this.
func insert(root *ListNode, elem int) *ListNode {
temp := ListNode{Val: elem, Next: nil}
if root.Val == 0 {
root = &temp
} else {
curr := root
for curr.Next != nil {
curr = curr.Next
}
curr = &temp
}
return root
}
The main functionality:
func convertToList(arr []int) *ListNode {
var head ListNode
for _, val := range arr {
head = *insert(&head, val)
}
return &head
}
A string function implementation to test the function:
func (l *ListNode) String() string {
x := make([]int, 0)
curr := l
for curr != nil {
x = append(x, curr.Val)
curr = curr.Next
}
return fmt.Sprint(x)
}
My main function to replicate output:
func main() {
arr := []int{1, 2, 3, 4, 5}
listNode := convertToList(arr)
fmt.Println(listNode.String())
}
Output:
[1]
Expected Output:
[1 2 3 4 5]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须更改
converttolist
和insert
函数为:和
converttolist
::You have to change your
convertToList
andinsert
functions as:and
convertToList
:更改
converttolist
:和
insert
:请参阅此类似:链接列表有关更多信息
Change
convertToList
:And
insert
:See this like : linked list for more information