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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度