Skip to content

Instantly share code, notes, and snippets.

@shreydesai
Created May 25, 2018 17:11
Show Gist options
  • Save shreydesai/a6a24ba426ae74d07e9ebf03813ccfaa to your computer and use it in GitHub Desktop.
Save shreydesai/a6a24ba426ae74d07e9ebf03813ccfaa to your computer and use it in GitHub Desktop.
Singly linked list in Go
package main
import "fmt"
// Node data structure
type Node struct {
data int
next *Node
}
// LinkedList data structure
type LinkedList struct {
head *Node
size int
}
// Init initializes the Linked List
func (l *LinkedList) Init() {
l.head = nil
l.size = 0
}
// Size reports the length of the Linked List
func (l *LinkedList) Size() int {
return l.size
}
// Append adds data to the end of the Linked List
func (l *LinkedList) Append(data int) {
node := &Node{data: data}
if l.head == nil {
l.head = node
} else {
temp := l.head
for temp.next != nil {
temp = temp.next
}
temp.next = node
}
l.size++
}
// Remove deletes data from the Linked List
func (l *LinkedList) Remove(data int) bool {
if l.head == nil {
return false
}
if l.head.data == data {
l.head = l.head.next
l.size--
return true
}
prev := (*Node)(nil)
curr := l.head
for curr != nil {
if curr.data == data {
prev.next = curr.next
l.size--
return true
}
prev = curr
curr = curr.next
}
return false
}
// Print outputs the Linked List
func (l *LinkedList) Print() {
temp := l.head
for temp != nil {
fmt.Printf("%d ", temp.data)
temp = temp.next
}
fmt.Printf("\n")
}
func main() {
linkedList := new(LinkedList)
linkedList.Init()
for i := 0; i < 10; i++ {
linkedList.Append(i)
fmt.Printf("Adding %d, Size %d\n", i, linkedList.Size())
linkedList.Print()
fmt.Printf("\n")
}
for i := 0; i <= 10; i++ {
linkedList.Remove(10 - i)
fmt.Printf("Removing %d, Size %d\n", 10-i, linkedList.Size())
linkedList.Print()
fmt.Printf("\n")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment