|
|
|
////////////////////////////////////////////////
|
|
|
|
// Linked List Node
|
|
|
|
|
|
|
|
// Start by defining a node.
|
|
|
|
// The data type is interface{}, which means we can define a type as a struct, just like we do here, and pass it as a data type.
|
|
|
|
// A linked list node is a burrito for data.
|
|
|
|
type Node struct {
|
|
|
|
data interface{}
|
|
|
|
next *Node
|
|
|
|
}
|
|
|
|
|
|
|
|
// Define an Append function for the Node struct.
|
|
|
|
// This appends some data to the linked list, right after node n (not at the end).
|
|
|
|
// Defined for this type
|
|
|
|
// \/\/\/
|
|
|
|
// Returns this type
|
|
|
|
// \/\/\/
|
|
|
|
func ( n *Node ) Append(data interface{}) *Node {
|
|
|
|
|
|
|
|
// If we are on the last node at the end of the list:
|
|
|
|
if n.Next == nil {
|
|
|
|
// The next item in the list is the data we are appending
|
|
|
|
n.Next = &Node{ data, nil }
|
|
|
|
|
|
|
|
} else {
|
|
|
|
// The next item in the list is the data we are appending,
|
|
|
|
// but we also link it to the (old) next item in the list,
|
|
|
|
// so we don't lose that data forever.
|
|
|
|
tmp := &Node{data, n.next}
|
|
|
|
n.Next = tmp
|
|
|
|
}
|
|
|
|
// Now return a pointer that points at the new node.
|
|
|
|
return n.Next
|
|
|
|
}
|
|
|
|
|
|
|
|
// Define a Print function for the Node struct.
|
|
|
|
// This prints the data.
|
|
|
|
func (n *Node) String() string {
|
|
|
|
return fmt.Sprintf("Node: %v", n.data)
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
////////////////////////////////////////////////
|
|
|
|
// Linked List
|
|
|
|
|
|
|
|
type LinkedList struct {
|
|
|
|
root Node*
|
|
|
|
}
|
|
|
|
|