Skip to content

Instantly share code, notes, and snippets.

@tuxido-feynman
Created November 10, 2019 06:56
Show Gist options
  • Save tuxido-feynman/00156ddb20fdd3f2c45d9ce489686985 to your computer and use it in GitHub Desktop.
Save tuxido-feynman/00156ddb20fdd3f2c45d9ce489686985 to your computer and use it in GitHub Desktop.
linked list
package linkedlistsingle
import "fmt"
type node struct {
Next *node
Value int
}
//LinkedList is a data structure for storing data in nodes with references to each other
type LinkedList struct {
head *node
tail *node
}
func (linked LinkedList) String() string {
var result string
for current := linked.head; current != nil; current = current.Next {
result += fmt.Sprintf("%d-->", current.Value)
}
return result
}
//Add method on LinkedList which inserts an integer into the data structure
func (linked *LinkedList) Add(val int) {
n := node{Value: val}
if linked.head == nil {
linked.head, linked.tail = &n, &n
} else {
linked.tail.Next = &n
linked.tail = &n
}
}
//Contains traverses list looking for paramter v, returns true if v is in list
func (linked *LinkedList) Contains(v int) bool {
for current := linked.head; current != nil; current = current.Next {
if current.Value == v {
return true
}
}
return false
}
//Remove node by value from linked list
func (linked *LinkedList) Remove(v int) bool {
if linked.head == nil {
return false
}
if linked.head.Value == v {
if linked.head == linked.tail {
linked.head, linked.tail = nil, nil
} else {
linked.head = linked.head.Next
}
return true
}
for current := linked.head; current.Next != nil; current = current.Next {
if current.Next.Value == v {
if linked.tail == current.Next {
current.Next = nil
linked.tail = current
} else {
current.Next = current.Next.Next
}
return true
}
}
return false
}
//Reverse reverses the linked list
func (linked *LinkedList) Reverse() {
var prev *node
current := linked.head
linked.tail = current
for current != nil {
next := current.Next
current.Next = prev
prev = current
current = next
}
linked.head = prev
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment