Skip to content

Instantly share code, notes, and snippets.

@amulyakashyap09
Created August 11, 2018 12:17
Show Gist options
  • Save amulyakashyap09/76e5c503709195d12130b75b773279db to your computer and use it in GitHub Desktop.
Save amulyakashyap09/76e5c503709195d12130b75b773279db to your computer and use it in GitHub Desktop.
Linked List operations in golang
package main
import (
"fmt"
"errors"
)
type Node struct {
value int32
next *Node
}
type List struct {
head *Node
tail *Node
}
func (L *List) Insert(data int32){
node:= &Node{value: data}
if L.head == nil {
L.head = node
}else {
L.tail.next = node
}
L.tail = node
}
func (L *List) First() *Node {
return L.head
}
func (L *List) Front(data int32) {
node:= &Node{value: data}
node.next = L.head
L.head = node
}
func (L *List) After(prevNode *Node, data int32) error {
var err error
if prevNode == nil {
err = errors.New("Previous node cannot be null")
}else{
node:= &Node{value: data}
prevNode.next = node.next
prevNode.next = node
}
return err
}
func (L *List) Reverse(head *Node) {
if head.next == nil {
fmt.Println("Rev : ", head.value)
}else {
fmt.Println("Rev : ", head.value)
L.Reverse(head.next)
}
}
func (N *Node) Next() *Node {
return N.next
}
func main() {
l:= &List{}
l.Insert(1)
l.Insert(2)
//l.After(l.head, 12)
l.Insert(3)
l.Insert(4)
l.Insert(5)
l.Front(10)
n := l.First()
l.Reverse(n)
// fmt.Println(" Reverse : ", l.Reverse(n))
for {
fmt.Println(n.value)
n = n.Next()
if n == nil {
break
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment