Created
March 10, 2018 19:52
-
-
Save frankcash/579ba83c8c7031c3d1a9eab921ef0d6f to your computer and use it in GitHub Desktop.
simple linked list in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"fmt" | |
) | |
type node struct { | |
prev *node | |
data string | |
} | |
// append will append the node at the end of the linked list | |
func (orig *node) append(next *node) { | |
if orig.prev != nil { | |
orig.prev.append(next) | |
} else { | |
orig.prev = next | |
} | |
} | |
// findNode will find a node by the desired value | |
func (orig *node) findNode(val string) (res *node) { | |
if orig.data == val { | |
return orig | |
} | |
return orig.prev.findNode(val) | |
} | |
// nthFromLast will return the nth from last node | |
func nthFromLast(head *node, n int) (*node, error) { | |
if head.prev == nil || n < 1 { | |
return nil, errors.New("invalid") | |
} | |
p1 := head | |
p2 := head | |
for j := 0; j < n; j++ { | |
// while moving p2 check if it becomes NULL, that is if it reaches the end | |
// of the list. That would mean the list has less than n nodes, so its not | |
// possible to find nth from last, so return NULL. | |
if p2.prev == nil { | |
return nil, errors.New("end") | |
} | |
// move p2 forward. | |
p2 = p2.prev | |
} | |
for { | |
if p2.prev != nil { | |
p1 = p1.prev | |
p2 = p2.prev | |
} else { | |
break | |
} | |
} | |
return p1, nil | |
} | |
func (orig *node) print() { | |
if orig.prev != nil { | |
orig.prev.print() | |
fmt.Println(orig.data) | |
} else { | |
fmt.Println(orig.data) | |
} | |
} | |
func genList() *node { | |
first := node{} | |
second := node{} | |
third := node{} | |
fourth := node{} | |
first.data = "fizz" | |
second.data = "buzz" | |
third.data = "foo" | |
fourth.data = "bar" | |
// second.prev = &first | |
first.append(&second) | |
first.append(&third) | |
first.append(&fourth) | |
return &first | |
} | |
func main() { | |
list := genList() | |
list.print() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment