|
| 1 | +// Implementing a DoubleLinkedList data structure in go |
| 2 | +// We'll implement Append, Prepend and Remove methods |
| 3 | +// of a typical DoubleLinkedList |
| 4 | + |
| 5 | + |
| 6 | +package main |
| 7 | + |
| 8 | +import ( |
| 9 | + "errors" |
| 10 | +) |
| 11 | + |
| 12 | +// LinkedList represents our list with it's properties |
| 13 | +type DoubleLinkedList struct { |
| 14 | + Head *DoubleNode |
| 15 | + Tail *DoubleNode |
| 16 | + Length int |
| 17 | +} |
| 18 | + |
| 19 | +// Append adds a node to the end of the list |
| 20 | +func (list *DoubleLinkedList) Append(newNode *DoubleNode) { |
| 21 | + |
| 22 | + if list.Length == 0 { |
| 23 | + list.Head = newNode |
| 24 | + list.Tail = newNode |
| 25 | + } else { |
| 26 | + lastNode := list.Tail |
| 27 | + |
| 28 | + lastNode.Next = newNode |
| 29 | + newNode.Before = lastNode |
| 30 | + |
| 31 | + list.Tail = newNode |
| 32 | + } |
| 33 | + |
| 34 | + list.Length++ |
| 35 | + |
| 36 | +} |
| 37 | + |
| 38 | +// Prepend adds a node to the start of the list |
| 39 | +func (list *DoubleLinkedList) Prepend(newNode *DoubleNode) { |
| 40 | + |
| 41 | + if list.Length == 0 { |
| 42 | + list.Head = newNode |
| 43 | + list.Tail = newNode |
| 44 | + } else { |
| 45 | + firstNode := list.Head |
| 46 | + list.Head = newNode |
| 47 | + newNode.Next = firstNode |
| 48 | + } |
| 49 | + |
| 50 | + list.Length++ |
| 51 | + |
| 52 | +} |
| 53 | + |
| 54 | +// Remove removes a node from the list |
| 55 | +// This has to iterate through the whole list |
| 56 | +// to try find the node to remove |
| 57 | +// Can be performance costly with large lists |
| 58 | +// You might choose to use Arrays in this case |
| 59 | +// where we can identify an element by Index |
| 60 | + |
| 61 | +func (list *DoubleLinkedList) Remove(node *DoubleNode) { |
| 62 | + |
| 63 | + if list.Length == 0 { |
| 64 | + panic(errors.New("cannot remove element on an empty list")) |
| 65 | + } |
| 66 | + |
| 67 | + var previousPost *DoubleNode |
| 68 | + currentPost := list.Head |
| 69 | + |
| 70 | + for currentPost.Value != node.Value { |
| 71 | + if currentPost.Next == nil { |
| 72 | + panic(errors.New("no such element found with value")) |
| 73 | + } |
| 74 | + |
| 75 | + previousPost = currentPost |
| 76 | + currentPost = currentPost.Next |
| 77 | + } |
| 78 | + |
| 79 | + previousPost.Next = currentPost.Next |
| 80 | + |
| 81 | + list.Length-- |
| 82 | + |
| 83 | +} |
0 commit comments