Jonathan M. Hollin wrote to [EMAIL PROTECTED]:

> Can anyone offer me some pointers (pun intended) on how to implement
> a stack in Perl with an array?

Perl has two simple builtin functions for treating an array like a
stack. See push() and pop().

Basically:

my @stack;

push @stack, "e3";
push @stack, "e2";
push @stack, "e1";

print pop(@stack);
print pop(@stack);
print pop(@stack);

Output is:

e1e2e3

> I need to have an array of elements as follows:
>
> 0 - e1
> 1 - e2
> 2 - e3
> ...
>
> And I need to be able to insert items:
>
> e4 needs to go into $array[1].

Does it *have* to? That would be expensive. push() and pop() keep the
head element at the end of the array, so push() and pop() are each
O(1) operations.

By rearranging the array for every push() and pop() to keep the head
at [1] (or [0]), your operations are now O(n).

> 1 and 2 need to move down (or up or left or right - depending on how
> you visualise arrays) yet retain their contents:

Again, expensive. I can't think of a reason you'd need to do this for
a traditional stack. Even if you're extending the idea of a stack to
include other functions, you probably just need to reverse your logic
to start from the last element of the array.


> And, you guessed it, I need to be able to remove elements, and have
> the others move down...

pop()


> How do I implement this in code anyone?

See above. push() and pop() are very simple functions you could write
yourself in about 1 line apiece. Fortunately, you don't have to. :-)

- Ryan

-- 
  Ryan Thompson <[EMAIL PROTECTED]>

  SaskNow Technologies - http://www.sasknow.com
  901 1st Avenue North - Saskatoon, SK - S7K 1Y4

        Tel: 306-664-3600   Fax: 306-244-7037   Saskatoon
  Toll-Free: 877-727-5669     (877-SASKNOW)     North America

Reply via email to