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

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

Is it possible to create new linked list nodes inside a loop in goLang?

问题

我需要为链表创建节点,并在函数中返回头节点。

每个节点的定义如下:

  1. type ListNode struct {
  2. Val int
  3. Next *ListNode
  4. }

这是函数的代码:

  1. func addTwoNumbers(l1 *ListNode, l2 *ListNode) []string {
  2. calculateValue := func(l *ListNode) int {
  3. var sumsum int
  4. element := l
  5. weight := 1
  6. for element != nil {
  7. sumsum = sumsum + element.Val*weight
  8. weight = weight * 10
  9. element = element.Next
  10. }
  11. return sumsum
  12. }
  13. numstr := strconv.Itoa(calculateValue(l1) + calculateValue(l2))
  14. listsum := strings.Split(numstr, "")
  15. return listsum
  16. }

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

因此,想法是通过使用for循环迭代列表,在for循环内部创建节点并将它们链接在一起。在return语句之前,代码应该类似于以下内容(在addTwoNumbers函数内部):

  1. for _, element := range listsum{
  2. // 在这里创建节点并链接它们
  3. }

有没有办法实现这个需求?

英文:

I need to create a nodes for a linked list and return the head inside a Function.

Definition for each node:

  1. type ListNode struct {
  2. Val int
  3. Next *ListNode
  4. }

This is the function:

  1. func addTwoNumbers(l1 *ListNode, l2 *ListNode) []string {
  2. calculateValue := func(l *ListNode) int {
  3. var sumsum int
  4. element := l
  5. weight := 1
  6. for element != nil {
  7. sumsum = sumsum + element.Val*weight
  8. weight = weight * 10
  9. element = element.Next
  10. }
  11. return sumsum
  12. }
  13. numstr := strconv.Itoa(calculateValue(l1) + calculateValue(l2))
  14. listsum := strings.Split(numstr, "")
  15. return listsum
  16. }

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):

  1. for _, element := range listsum{
  2. }

Is there a way this can be done?

答案1

得分: 0

在评论中提到的解决方案

  1. // 使用第一个元素的值创建头节点
  2. head := &ListNode{ Val: listSum[0] }
  3. tail := head
  4. // 遍历剩余的值
  5. for _, sum := range listSum[1:] {
  6. node := &ListNode{ Val: sum }
  7. tail.Next = node // 将节点追加到链表中
  8. tail = node // 将尾指针更改为当前添加的节点
  9. }
英文:

Solution mentioned in comment

  1. // create head with the value from first element
  2. head := &ListNode{ Val: listSum[0] }
  3. tail := head
  4. // range remaining values
  5. for _, sum := range listSum[1:] {
  6. node := &ListNode{ Val: sum }
  7. tail.Next = node // append node to list
  8. tail = node // change tail pointer to currently added node
  9. }

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:

确定