Skip to content

Instantly share code, notes, and snippets.

@LordRahl90
Last active October 31, 2018 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LordRahl90/72ba610d39700347ce24d00ca54a5cb8 to your computer and use it in GitHub Desktop.
Save LordRahl90/72ba610d39700347ce24d00ca54a5cb8 to your computer and use it in GitHub Desktop.
Attempt to create a linked list in golang. Well, I have issues with the insertBefore. Working on the delete node as well.
package main
import (
"fmt"
)
func main() {
llist := &LinkedList{}
llist.Head = &Node{Data: 10}
second := Node{Data: 30}
third := Node{Data: 45}
fourth := Node{Data: 88}
fifth := Node{Data: 89}
fourth.Next = &fifth
third.Next = &fourth
second.Next = &third
llist.Head.Next = &second
llist.addAtFirst(78)
llist.addAfterNode(66, &third)
llist.addAtEnd(39)
llist.printLinkedList()
}
//Node entity struct
type Node struct {
Data int
Next *Node
}
//LinkedList struct
type LinkedList struct {
Head *Node
}
//Iterates through the list to print each element.
//Thinking about implementing the recursive part.
func (list LinkedList) printLinkedList() {
n := list.Head
for n != nil {
fmt.Printf("%d\n", n.Data)
n = n.Next
}
// println(n.Data)
}
//Adds a new node at the head of the list.
func (list *LinkedList) addAtFirst(data int) {
newNode := Node{Data: data}
prevNode := list.Head
if prevNode == nil {
list.Head = &newNode
}
newNode.Next = prevNode
list.Head = &newNode
}
//Adds a new node after a specified node.
func (list *LinkedList) addAfterNode(data int, prevNode *Node) {
if prevNode == nil {
fmt.Println("The previous node doesnt exist in the list.")
return
}
newNode := Node{Data: data}
newNode.Next = prevNode.Next
prevNode.Next = &newNode
}
//Adds value at the end of the linked list.
func (list *LinkedList) addAtEnd(data int) {
newNode := Node{Data: data}
n := list.Head
for n.Next != nil {
n = n.Next
}
n.Next = &newNode
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment