Contributed by GrandFather
on Jun 17, 2005 at 02:26 UTC
> Data Structures
|Answer: How do I make a stack?|
contributed by GrandFather
Perl arrays are a really simple way of implementing stacks and related data structures. The key is to realise that you can access the ends of the array using  for the left/bottom/start of the array and [-1] for the right/top/end of the array.
With that in mind you can either use unshift/shift to add/remove items at the start, or push/pop to add/remove things at the end of the array and implement a stack. The following pushes an item onto a stack, accesses it (at the top of the stack), then pops it off again:
push @stack, "An item to push on the stack";
print "The top stack item is: $stack[-1]\n";
Using unshift/shift/ gives stack semantics as does push/pop/[-1].
Using push/shift/ or unshift/pop/[-1] gives queue semantics.
push/pop/shift/unshift will return undef if the stack/queue was empty. If you may
be intentionally placing undef values in the stack, you can still check if it is empty: scalar(@stack) returns the number of elements on the stack.
By combining these and adding splice to the mix you can do some really nifty stuff that combine stack, list and queue sematics in one data structure.
For info on splice see How do I insert an element into an arbitrary (in range) array index? and How do I completely remove an element from an array?.
Please (register and) log in if you wish to add an answer
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
Outside of code tags, you may need to use entities for some characters:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
| & || & |
| < || < |
| > || > |
| [ || [ |
| ] || ] ||