英文:
Is it possible to create new linked list nodes inside a loop in goLang?
问题
我需要为链表创建节点,并在函数中返回头节点。
每个节点的定义如下:
type ListNode struct {
Val int
Next *ListNode
}
这是函数的代码:
func addTwoNumbers(l1 *ListNode, l2 *ListNode) []string {
calculateValue := func(l *ListNode) int {
var sumsum int
element := l
weight := 1
for element != nil {
sumsum = sumsum + element.Val*weight
weight = weight * 10
element = element.Next
}
return sumsum
}
numstr := strconv.Itoa(calculateValue(l1) + calculateValue(l2))
listsum := strings.Split(numstr, "")
return listsum
}
目前,该函数返回一个字符串列表,每个字符串应分配给每个节点的Val
(Val
是一个整数,目前列表中的元素是字符串,稍后可以处理)。
因此,想法是通过使用for
循环迭代列表,在for
循环内部创建节点并将它们链接在一起。在return
语句之前,代码应该类似于以下内容(在addTwoNumbers
函数内部):
for _, element := range listsum{
// 在这里创建节点并链接它们
}
有没有办法实现这个需求?
英文:
I need to create a nodes for a linked list and return the head inside a Function.
Definition for each node:
type ListNode struct {
Val int
Next *ListNode
}
This is the function:
func addTwoNumbers(l1 *ListNode, l2 *ListNode) []string {
calculateValue := func(l *ListNode) int {
var sumsum int
element := l
weight := 1
for element != nil {
sumsum = sumsum + element.Val*weight
weight = weight * 10
element = element.Next
}
return sumsum
}
numstr := strconv.Itoa(calculateValue(l1) + calculateValue(l2))
listsum := strings.Split(numstr, "")
return listsum
}
Right now the function returns a list of strings, each string should be assigned to Val
in each node.(Val is an integer and right now the list is of string I can handle that later).
So the idea would be to iterate through a list with a for loop and create the nodes and link them together inside a for. It would look something like this (inside addTwoNumbers
before the return):
for _, element := range listsum{
}
Is there a way this can be done?
答案1
得分: 0
在评论中提到的解决方案
// 使用第一个元素的值创建头节点
head := &ListNode{ Val: listSum[0] }
tail := head
// 遍历剩余的值
for _, sum := range listSum[1:] {
node := &ListNode{ Val: sum }
tail.Next = node // 将节点追加到链表中
tail = node // 将尾指针更改为当前添加的节点
}
英文:
Solution mentioned in comment
// create head with the value from first element
head := &ListNode{ Val: listSum[0] }
tail := head
// range remaining values
for _, sum := range listSum[1:] {
node := &ListNode{ Val: sum }
tail.Next = node // append node to list
tail = node // change tail pointer to currently added node
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论