datatypes: add push_many for doubly and singly linked list + add insert_many for heap (#19975)

This commit is contained in:
Odai Alghamdi 2023-11-24 10:40:08 +03:00 committed by GitHub
parent be544d73f3
commit e8ce02b50a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 87 additions and 12 deletions

View file

@ -1,5 +1,10 @@
module datatypes
enum Direction {
front
back
}
struct DoublyListNode[T] {
mut:
data T
@ -79,6 +84,22 @@ pub fn (mut list DoublyLinkedList[T]) push_front(item T) {
list.len += 1
}
// push_many adds array of elements to the beginning of the linked list
pub fn (mut list DoublyLinkedList[T]) push_many(elements []T, direction Direction) {
match direction {
.front {
for v in elements {
list.push_front(v)
}
}
.back {
for v in elements {
list.push_back(v)
}
}
}
}
// pop_back removes the last element of the linked list
pub fn (mut list DoublyLinkedList[T]) pop_back() !T {
if list.is_empty() {

View file

@ -48,6 +48,24 @@ fn test_push() {
assert list.last()! == 3
}
fn test_push_many_back() {
mut list := DoublyLinkedList[int]{}
elem := [1, 2, 3]
list.push_many(elem, Direction.back)
assert list.last()! != 1
assert list.last()! != 2
assert list.last()! == 3
}
fn test_push_many_front() {
mut list := DoublyLinkedList[int]{}
mut elem := [1, 2, 3]
list.push_many(elem, Direction.back)
elem = [111]
list.push_many(elem, Direction.front)
assert list.first()! == 111
}
fn test_pop() {
mut list := DoublyLinkedList[int]{}
list.push_back(1)

View file

@ -20,6 +20,13 @@ pub fn (mut heap MinHeap[T]) insert(item T) {
}
}
// insert array of elements to the heap.
pub fn (mut heap MinHeap[T]) insert_many(elements []T) {
for v in elements {
heap.insert(v)
}
}
// pop removes the top-most element from the heap.
pub fn (mut heap MinHeap[T]) pop() !T {
if heap.data.len == 0 {

View file

@ -18,6 +18,17 @@ fn test_min_heap() {
}
}
fn test_min_heap_insert_many() {
mut heap := MinHeap[int]{}
elem := [2, 0, 8, 4, 1]
heap.insert_many(elem)
assert heap.pop()! == 0
assert heap.peek()! == 1
heap.pop()!
assert heap.peek()! == 2
}
struct Item {
data string
priority int

View file

@ -81,6 +81,13 @@ pub fn (mut list LinkedList[T]) push(item T) {
list.len += 1
}
// push adds an array of elements to the end of the linked list
pub fn (mut list LinkedList[T]) push_many(elements []T) {
for v in elements {
list.push(v)
}
}
// pop removes the last element of the linked list
pub fn (mut list LinkedList[T]) pop() !T {
if unsafe { list.head == 0 } {

View file

@ -27,6 +27,17 @@ fn test_first() {
assert false
}
fn test_push_many() {
mut list := LinkedList[int]{}
x := [1, 2, 3, 4, 5]
list.push_many(x)
assert list.first()! == 1
assert list.first()! == 1
list = LinkedList[int]{}
list.first() or { return }
assert false
}
fn test_last() {
mut list := LinkedList[int]{}
list.push(1)