dshu1235 2015-01-06 10:49
浏览 18
已采纳

实现“通用”节点列表

I'd like to implement a linked list with nodes. Each node can be of a different type (Foo, Bar and Baz - will be 40-50 different nodes) and each type has common fields (prev, next, ...) and some node-specific fields.

I have a hard time to come up with a solution that looks reasonable. Now the question: what approach can I take to make this more elegant?

Here is my (dummy) main.go:

package main

import (
    "fmt"

    "node"
)

func main() {
    a := node.NewFoo()
    fmt.Println(a)

    b := node.NewBar()
    fmt.Println(b)

    node.Append(a, b)
}

and here is my implementation (node.go):

package node

type Node interface {
}

type FooNode struct {
    prev               Node
    next               Node
    FieldSpecificToFoo int
}

type BarNode struct {
    prev               Node
    next               Node
    FieldSpecificToBar int
}

type BazNode struct {
    prev               Node
    next               Node
    FieldSpecificToBaz int
}

func NewFoo() *FooNode {
    return &FooNode{}
}

func NewBar() *BarNode {
    return &BarNode{}
}

func NewBaz() *BazNode {
    return &BazNode{}
}

func Append(a, b Node) {
    // set next and prev pointer
    switch v := a.(type) {
    case FooNode:
        v.next = b
    case BarNode:
        v.next = b
    case BazNode:
        v.next = b
    }

    switch v := b.(type) {
    case FooNode:
        v.prev = a
    case BarNode:
        v.prev = a
    case BazNode:
        v.prev = a
    }
}

This is obviously a pretty crappy implementation. What can I do in this case?

  • 写回答

1条回答 默认 最新

  • dtujfmfs06058 2015-01-06 10:58
    关注

    I am not entirely sure I understand what you are trying to do but here are a few ideas:

    • Use the standard container
    • Make the node contain your "user" data as an interface:

      type Node struct {
          next *Node
          Value interface{}
      }
      

    This is (somewhat) like doing it in C with a void* to user data.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大