Queue and Stack Using an Array

This Tech-Recipes tutorial contains a series of operations on an array. We can use these functions to implement a queue or a stack that can be of better use to us.


push:
array=(“${array[@]}” $new_element)

pop:
array=(${array[@]:0:$((${#array[@]}-1))})

shift:
array=(${array[@]:1})

unshift
array=($new_element “${array[@]}”)

function del_array {
local i
for (( i = 0 ; i < ${#array[@]} ; i++ ))
do
if [ "$1" = "${array[$i]}" ] ;then
break
fi
done
del_array_index $i
}

function del_array_index {
array=(${array[@]:0:$1} ${array[@]:$(($1 + 1))})
}

The Conversation

Follow the reactions below and share your own thoughts.

2 Responses to “Queue and Stack Using an Array”

  1. December 19, 2008 at 10:03 pm, Jerry Hamilton said:

    Not enough documentation as to the WHAT and the WHY

    Reply

  2. August 21, 2009 at 5:31 pm, Nicolas Marchildon said:

    Thanks for sharing! This shows how bad Bash is as a programming language!

    Reply

Leave a Reply