1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

datatypes: add array() method for LinkedList, DoublyLinkedList, Queue, and Stack (#15524) (#15525)

This commit is contained in:
shove 2022-08-25 19:12:39 +08:00 committed by GitHub
parent c662431cfd
commit 723b3d74ee
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 52 additions and 2 deletions

View File

@ -249,13 +249,18 @@ pub fn (mut list DoublyLinkedList<T>) delete(idx int) {
// str returns a string representation of the linked list
pub fn (list DoublyLinkedList<T>) str() string {
return list.array().str()
}
// array returns a array representation of the linked list
pub fn (list DoublyLinkedList<T>) array() []T {
mut result_array := []T{}
mut node := list.head
for unsafe { node != 0 } {
result_array << node.data
node = node.next
}
return result_array.str()
return result_array
}
// next implements the iter interface to use DoublyLinkedList with

View File

@ -158,3 +158,11 @@ fn test_str() ? {
list.push_back(3)
assert list.str() == '[1, 2, 3]'
}
fn test_array() ? {
mut list := DoublyLinkedList<int>{}
list.push_back(1)
list.push_back(2)
list.push_back(3)
assert list.array() == [1, 2, 3]
}

View File

@ -147,11 +147,16 @@ pub fn (mut list LinkedList<T>) prepend(item T) {
// str returns a string representation of the linked list
pub fn (list LinkedList<T>) str() string {
return list.array().str()
}
// array returns a array representation of the linked list
pub fn (list LinkedList<T>) array() []T {
mut result_array := []T{}
mut node := list.head
for unsafe { node != 0 } {
result_array << node.data
node = node.next
}
return result_array.str()
return result_array
}

View File

@ -112,3 +112,11 @@ fn test_str() ? {
list.push(3)
assert list.str() == '[1, 2, 3]'
}
fn test_array() ? {
mut list := LinkedList<int>{}
list.push(1)
list.push(2)
list.push(3)
assert list.array() == [1, 2, 3]
}

View File

@ -44,3 +44,8 @@ pub fn (mut queue Queue<T>) pop() ?T {
pub fn (queue Queue<T>) str() string {
return queue.elements.str()
}
// array returns a array representation of the queue
pub fn (queue Queue<T>) array() []T {
return queue.elements.array()
}

View File

@ -69,3 +69,10 @@ fn test_pop() ? {
queue.pop() or { return }
assert false
}
fn test_array() ? {
mut queue := Queue<int>{}
queue.push(1)
queue.push(2)
assert queue.array() == [1, 2]
}

View File

@ -34,3 +34,8 @@ pub fn (mut stack Stack<T>) pop() ?T {
pub fn (stack Stack<T>) str() string {
return stack.elements.str()
}
// array returns a array representation of the stack
pub fn (stack Stack<T>) array() []T {
return stack.elements
}

View File

@ -50,3 +50,10 @@ fn test_pop() ? {
stack.pop() or { return }
assert false
}
fn test_array() ? {
mut stack := dt.Stack<int>{}
stack.push(1)
stack.push(2)
assert stack.array() == [1, 2]
}