Skip to content

Instantly share code, notes, and snippets.

@typable
Last active April 28, 2021 15:19
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 typable/3c3e703c27e8a8379c6dace3ea5d3015 to your computer and use it in GitHub Desktop.
Save typable/3c3e703c27e8a8379c6dace3ea5d3015 to your computer and use it in GitHub Desktop.
LinkedList - Go
package main
type Node struct {
val int
ref *Node
}
type Linkedlist struct {
list *Node
}
func (l *Linkedlist) New(arr ...int) {
l.list = Write(arr)
}
func (l *Linkedlist) Push(val int) {
if l.Initial() {
return
}
node := &Node{val, nil}
node.ref = l.list
l.list = node
}
func (l *Linkedlist) Pop() int {
if l.Initial() {
return -1
}
val := l.list.val
l.list = l.list.ref
return val
}
func (l *Linkedlist) Shift() int {
if l.Initial() {
return -1
}
var last *Node
node := l.list
for node.ref != nil {
last = node
node = node.ref
}
last.ref = nil
return node.val
}
func (l *Linkedlist) Remove(i int) int {
if l.Initial() {
return -1
}
count := 1
size := l.Size()
if i >= size {
return -1
}
var last *Node
node := l.list
for node.ref != nil {
if size - count == i {
if last == nil {
return l.Pop()
}
last.ref = node.ref
return node.val
}
last = node
node = node.ref
count++
}
return l.Shift()
}
func (l *Linkedlist) Values() []int {
if l.Initial() {
return []int{}
}
return Read(l.list)
}
func (l *Linkedlist) Size() int {
if l.Initial() {
return 0
}
count := 1
node := l.list
for node.ref != nil {
node = node.ref
count++
}
return count
}
func (l *Linkedlist) Initial() bool {
return l.list == nil
}
func Write(arr []int) *Node {
list := &Node{arr[0], nil}
for i, val := range arr {
if i > 0 {
node := &Node{val, nil}
node.ref = list
list = node
}
}
return list
}
func Read(list *Node) []int {
arr := []int{}
if list.ref != nil {
arr = append(arr, Read(list.ref)...)
}
arr = append(arr, list.val)
return arr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment