Created
September 10, 2023 12:07
-
-
Save gabrielbussolo/90af5ea972ce1f5746f620a36b8357bb to your computer and use it in GitHub Desktop.
Simple queue implementation 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 "fmt" | |
type Queue struct { | |
Head *Node | |
Tail *Node | |
} | |
type Node struct { | |
data int | |
next *Node | |
} | |
func (q *Queue) Enqueue(element int) { | |
newNode := Node{data: element} | |
if q.Head == nil { | |
q.Head = &newNode | |
q.Tail = &newNode | |
return | |
} | |
q.Tail.next = &newNode | |
q.Tail = &newNode | |
} | |
func (q *Queue) Dequeue() { | |
//investigate if garbage collector eliminate the actual head (i dont think so bcz still have a refence to next) | |
q.Head = q.Head.next | |
} | |
func (q *Queue) Peek() int { | |
return q.Head.data | |
} | |
func (q *Queue) Lookup(pos int) int { | |
current := q.Head | |
for i := 0; i < pos; i++ { | |
current = current.next | |
} | |
return current.data | |
} | |
func (q *Queue) Display() { | |
current := q.Head | |
for current != nil { | |
fmt.Printf(" %d <- ", current.data) | |
current = current.next | |
} | |
fmt.Println() | |
} | |
func main() { | |
q := Queue{} | |
q.Enqueue(5) | |
q.Enqueue(8) | |
q.Enqueue(3) | |
q.Enqueue(10) | |
q.Display() | |
q.Dequeue() | |
q.Display() | |
fmt.Println(q.Peek()) | |
fmt.Println(q.Lookup(1)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment