How to create and use Stack in Julia
Overview
In Julia, the Stack is a wrapper of a Deque type that provides interfaces for
Imagine a pile of tiles placed in vertical order. If we needed to grab a tile from the middle of the pile, we'd need to remove every tile on top of it first. This method is referred to as LIFO.
Operations
It mainly includes three operations:
push: Add an element to the stack.
pop: Remove an element from the stack.
peek: Get the topmost element of the stack.
Example
Below is a sample code for using a Stack in Julia:
using DataStructures# create a new Stacks = Stack{Int}()# push an item to the top of the stackpush!(s, 1)push!(s, 2)push!(s, 3)println("The stack is $(s)")println("The Length of stack is :", length(s) )println("The Top element of stack is :", first(s) )println("Removing last element of stack is :", pop!(s) )println("The stack is: $(s)")# emptying the stackempty!(s)println("After Emptying stack is: $(s)")
Explanation
Line 4: We create a
Stackobject with the names.Lines 7–9: We use the
push!()method to insert three elements into the stack.Line 13: We use the
length()method to get the number of elements of the stack.Line 14: We use the
first()method to get the element at the top of the stack.Line 15: We use the
pop!()method to remove the top element of the stack.Line 20: We use the
empty()method to remove all elements of the stack .
Note: The complete reference to the Stack can be found on the official
. Julia page https://juliacollections.github.io/DataStructures.jl/v0.11/stack_and_queue.html
Free Resources
- undefined by undefined
- undefined by undefined