How To Create a Linked List Using Golang

in #tech5 years ago

chain

Lately I started to practice my data structures to get a better grasp of programming. Today I chose to tackle the Linked List from scratch using Go. I have not had to write a linked list in forever which made this a great mental exercise.

Linked List Code Breakdown:

The first step I took was to create a struct. I know this struct needed to hold whatever data to store along with a link to the previous data. Here I set up the struct to hold an integer but this could be anything you want. The second is the link to the previous data and this has to be a pointer to an instance of the struct we just created.

type list struct {
    digi     int
    prevList *list
}

I followed that with a push method attached to the list type we just created. This will allow us at add new data to the list without rewriting the code. It starts by creating a variable called current of the list type we created. current will hold the data we need to set as the next node in the list, including the integer passed in and the pointer to the list calling the method. Then the method returns the pointer of the newly created current node.

func (l *list) push(num int) *list {
    var current list
    current.digi = num
    current.prevList = l
    return &current
}

Since I plan on turning this into a stack challenge, I followed the push method with a pop method. All this does is remove the most recent addition to the linked list by setting the previous data to the the current.

func (l *list) pop() {
    l.digi = l.prevList.digi
    l.prevList = l.prevList.prevList
}

I then follow up with main() to execute the methods mentioned above.

Linked List in Golang:

package main

import "fmt"

type list struct {
    digi     int
    prevList *list
}

// push adds another number to the stack
func (l *list) push(num int) *list {
    var current list
    current.digi = num
    current.prevList = l
    return &current
}

// pop removes the top most member from the stack
func (l *list) pop() {
    l.digi = l.prevList.digi
    l.prevList = l.prevList.prevList
}

func main() {
    var top *list
    // Create parts 0-9 of the stack
    for i := 0; i < 10; i++ {
        top = top.push(i)
    }

    top = top.push(10)
    fmt.Println(*top.prevList.prevList)
    fmt.Println(*top.prevList)
    fmt.Println(*top)
    top.pop()
    fmt.Println(*top)
}

Run the code at the Golang Playground
Originally posted on jrswab.com

Coin Marketplace

STEEM 0.24
TRX 0.22
JST 0.037
BTC 98245.75
ETH 3430.51
USDT 1.00
SBD 3.35