How To Create a Linked List Using Golang

in #tech5 years ago

chain

<p dir="auto">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. <h2>Linked List Code Breakdown: <p dir="auto">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. <pre><code>type list struct { digi int prevList *list } <p dir="auto">I followed that with a <code>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 <code>current of the list type we created. <code>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 <code>current node. <pre><code>func (l *list) push(num int) *list { var current list current.digi = num current.prevList = l return &current } <p dir="auto">Since I plan on turning this into a stack challenge, I followed the <code>push method with a <code>pop method. All this does is remove the most recent addition to the linked list by setting the previous data to the the current. <pre><code>func (l *list) pop() { l.digi = l.prevList.digi l.prevList = l.prevList.prevList } <p dir="auto">I then follow up with <code>main() to execute the methods mentioned above. <h2>Linked List in Golang: <pre><code>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) } <p dir="auto">Run the code at the <a href="https://play.golang.org/p/oTTBS6Q27Fc" target="_blank" rel="nofollow noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Golang Playground<br /> Originally posted on <a href="https://jrswab.com/blog/linked-list-golang" target="_blank" rel="nofollow noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">jrswab.com