Last active
August 12, 2023 12:21
-
-
Save romulets/7e374533f2df3cdf84bad3403add5d84 to your computer and use it in GitHub Desktop.
Quick implementation of a Queue (and Stack) using a double linked listed under the hood in go
This file contains hidden or 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
type doubleLinkedList struct { | |
head *linkedNode | |
tail *linkedNode | |
size int | |
} | |
type linkedNode struct { | |
val int | |
next *linkedNode | |
prev *linkedNode | |
} | |
func (q *doubleLinkedList) enqueue(val int) { | |
n := &linkedNode{val: val, next: nil, prev: nil} | |
if q.size == 0 { | |
q.head = n | |
} else if q.size == 1 { | |
n.prev = q.head | |
q.head.next = n | |
q.tail = n | |
} else { | |
n.prev = q.tail | |
q.tail.next = n | |
q.tail = n | |
} | |
q.size++ | |
} | |
func (q *doubleLinkedList) dequeue() int { | |
first := q.head | |
q.head = q.head.next | |
q.size-- | |
return first.val | |
} | |
func (q *doubleLinkedList) pop() int { | |
var last *linkedNode | |
// 1 | |
if q.size == 1 { | |
last = q.head | |
q.head = nil | |
q.tail = nil | |
// 1, 2 | |
} else if q.size == 2 { | |
last = q.tail | |
q.tail = nil | |
// 1, 2, 3 | |
} else { | |
last = q.tail | |
q.tail = last.prev | |
} | |
q.size-- | |
return last.val | |
} | |
func (q *doubleLinkedList) last() int { | |
if q.size == 1 { | |
return q.first() | |
} | |
return q.tail.val | |
} | |
func (q *doubleLinkedList) first() int { | |
return q.head.val | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment