doujiao4705 2018-02-08 21:34
浏览 71
已采纳

插入一个简单的单链表

I am trying to solve leetcode problem in Go to teach myself the language. I have a single linked list and an insert function:

type ListNode struct {
    Val int
    Next * ListNode
}


func Insert(listNode * ListNode, i int) {
    // @fixme how to check the first node?
    if listNode == nil {
        listNode.Val = i
        listNode.Next = nil
    } else {
        for;;
        listNode = listNode.Next {
            if listNode.Next == nil {
                listNode.Next = & ListNode {
                    i, nil
                }
                break
            }
        }
    }
}

func main() {

    vals: = [] int {
            1, 2, 3, 4, 5
        }
    var list ListNode
    for _,
    i: = range vals {
        Insert( & list, i)
    }
}

The problem is that when an instance of ListNode is instantiated the struct fields have zero values and I am unable update the set first element of the list because I am unable to check for it. In other words, that a ListNode item is initialized but empty. So when I want build a list 1->2->3->4->5 I end up having: 0->1 ->2 ...5 . The limitation is that I cannot change the struct definition as leetcode have that already defined. Here is a working example of the code above: https://play.golang.org/p/bIz-VjY1PS7

  • 写回答

1条回答 默认 最新

  • dongtan9518 2018-02-08 22:13
    关注

    What you should do is that you shouldn't use ListNode you should be using *ListNode, that way an empty list is represented by a nil *ListNode:

    func New() *ListNode {
        return nil
    }
    
    func Insert(listNode *ListNode, i int) *ListNode {
        // If it's nil, create it
        if listNode == nil {
            listNode = &ListNode{i, nil}
        } else {
            l := listNode
            for ; l.Next != nil; l = l.Next {
            }
            l.Next = &ListNode{i, nil}
        }
        return listNode
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料