Skip to content

Instantly share code, notes, and snippets.

@halkyon
Last active March 15, 2020 20:52
Show Gist options
  • Select an option

  • Save halkyon/89e78420e558e966e1f03b258d889fc7 to your computer and use it in GitHub Desktop.

Select an option

Save halkyon/89e78420e558e966e1f03b258d889fc7 to your computer and use it in GitHub Desktop.

Revisions

  1. halkyon revised this gist Mar 15, 2020. No changes.
  2. halkyon created this gist Mar 15, 2020.
    53 changes: 53 additions & 0 deletions linked-list.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,53 @@
    package main

    import (
    "fmt"
    )

    type list struct {
    head *item
    tail *item
    }

    type item struct {
    name string
    prev *item
    next *item
    }

    func main() {
    list := &list{}
    list.add(&item{name: "foo"})
    list.add(&item{name: "bar"})
    list.add(&item{name: "baz"})
    list.show()
    }

    func (list *list) add(item *item) {
    if list.head == nil {
    list.head = item
    } else {
    currentItem := list.tail
    currentItem.next = item
    item.prev = list.tail
    item.next = list.head
    list.head.prev = item
    }
    list.tail = item
    }

    func (list *list) show() {
    currentItem := list.head
    if currentItem == nil {
    return
    }

    fmt.Printf("%+v\n", currentItem)
    for currentItem.next != nil {
    currentItem = currentItem.next
    if currentItem == list.head {
    break
    }
    fmt.Printf("%+v\n", currentItem)
    }
    }