在Go语言中,可以在循环内部创建新的链表节点吗?

huangapple go评论84阅读模式
英文:

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

}

目前,该函数返回一个字符串列表,每个字符串应分配给每个节点的ValVal是一个整数,目前列表中的元素是字符串,稍后可以处理)。

因此,想法是通过使用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
}

huangapple
  • 本文由 发表于 2022年4月21日 21:27:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/71955315.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定