datatypes: add an index method on LinkedList and Queue (#13185)

pull/13192/head
Hunam 2022-01-16 18:11:10 +01:00 committed by GitHub
parent 2a3a4cfc84
commit db48594bd4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 49 additions and 3 deletions

View File

@ -40,6 +40,25 @@ pub fn (list LinkedList<T>) last() ?T {
}
}
// index returns the element at the given index of the linked list
pub fn (list LinkedList<T>) index(idx int) ?T {
if list.head == 0 {
return error('Linked list is empty')
} else {
mut node := list.head
mut iterations := 0
for node.next != 0 && iterations < idx {
node = node.next
iterations++
}
if iterations == idx {
return node.data
} else {
return error('Index out of bounds')
}
}
}
// push adds an element to the end of the linked list
pub fn (mut list LinkedList<T>) push(item T) {
new_node := &ListNode{

View File

@ -38,6 +38,17 @@ fn test_last() ? {
assert false
}
fn test_index() ? {
mut list := LinkedList<int>{}
list.push(1)
assert list.index(0) ? == 1
list.push(2)
assert list.index(1) ? == 2
list.pop() ?
list.index(1) or { return }
assert false
}
fn test_push() ? {
mut list := LinkedList<int>{}
list.push(1)

View File

@ -17,12 +17,17 @@ pub fn (queue Queue<T>) len() int {
// peek returns the head of the queue (first element added)
pub fn (queue Queue<T>) peek() ?T {
return if !queue.is_empty() { queue.elements.first() ? } else { error('Queue is empty') }
return queue.elements.first()
}
// last returns the tail of the queue (last element added)
pub fn (queue Queue<T>) last() ?T {
return if !queue.is_empty() { queue.elements.last() ? } else { error('Queue is empty') }
return queue.elements.last()
}
// index returns the element at the given index of the queue
pub fn (queue Queue<T>) index(idx int) ?T {
return queue.elements.index(idx)
}
// push adds an element to the tail of the queue
@ -32,7 +37,7 @@ pub fn (mut queue Queue<T>) push(item T) {
// pop removes the element at the head of the queue and returns it
pub fn (mut queue Queue<T>) pop() ?T {
return if !queue.is_empty() { queue.elements.shift() ? } else { error('Queue is empty') }
return queue.elements.shift()
}
// str returns a string representation of the queue

View File

@ -38,6 +38,17 @@ fn test_last() ? {
assert false
}
fn test_index() ? {
mut queue := Queue<int>{}
queue.push(1)
assert queue.index(0) ? == 1
queue.push(2)
assert queue.index(1) ? == 2
queue.pop() ?
queue.index(1) or { return }
assert false
}
fn test_push() ? {
mut queue := Queue<int>{}
queue.push(1)