Let’s Create a Node

In this article, we’ll define a Node data type, which will be the building block of several data structures that we’ll be learning further down the line.

Introduction

In this article, we’ll define a Node data type, which will be the building block of several data structures that we’ll be learning further down the line.

I will use Go for the majority of the algorithm design examples because of the language’s expressiveness, simplicity, and readability; however, the language choice does not really matter here. If you want adventure, feel free to replicate what you see here in your favorite language.

In these data structures and algorithms series, we’ll be writing quite a lot of Go. Before you begin, you may want to set up your Go development environment, if you haven’t already done so:

The Node User-Defined Data Type

Without further ado, here’s our guest of honor:

type Node struct {
Val interface{}
Next *Node
Prev *Node
}

We’ve created a Node type that contains a generic value (Val) and pointers to Nodes that come before and after itself.

package main

import "fmt"

type Node struct {
Val interface{}
Next *Node
Prev *Node
}

func main() {

// Create three Nodes.
n1 := &Node{Val: 10}
n2 := &Node{Val: 20}
n3 := &Node{Val: 30}

// Chain the nodes together.
//
// (n1) --next--> (n2) --next--> (n3)
// (n1) <--prev-- (n2) <--prev-- (n3)
n1.Next	= n2
n2.Next = n3
n3.Prev = n2
n2.Prev = n1

// The first node.
// The last node.
tail := n3

// Print nodes forward, starting from head to tail.
for node != nil {
fmt.Println("»»", node.Val)
node = node.Next
}

// Print nodes backwards, starting from tail to head.
node = tail
for node != nil {
fmt.Println("««", node.Val)
node = node.Prev
}
}

When you run the program, here’s how the output will be.

»» 10
»» 20
»» 30
«« 30
«« 20
«« 10

Conclusion

That wraps up this topic for now.

• A visual diagram of how the nodes point to each other.
• A quick introduction to setting up your Go development environment (so that you don’t have issues executing the above demo code)

Until then, may the source be with you 🦄.

\
\\,
\\\,^,.,,.                     Zero to Hero
,;7~((\))`;;,,               <zerotohero.dev>
,(@') ;)`))\;;',    stay up to date, be curious: learn
)  . ),((  ))\;,
/;`,,/7),)) )) )\,,
(& )`   (,((,((;( ))\,