improve.dk
Just another mindless drone looking for the perfect stack
posts - 227, comments - 489

Simple AS3 Stack Implementation

Written on April 21, 2010 by Mark S. Rasmussen in Development: AS/Flex/Flash

Recently I was doing some experimental AS3 development. Much to my surprise, simple collection classes like Stack/Queue are not available in the framework - guess I'm spoiled being used to the .NET Framework.

I ended up implementing a simple stack using an internal linked list. There's nothing exciting about the implementation but I thought others might be able to use it, so here it is :)

StackNode.as

package dk.improve.collections
{
    internal final class StackNode
    {
        public var value:Object;
        public var next:StackNode;
        
        public function StackNode(value:Object):void
        {
            this.value = value;
        }
    }
}

Stack.as

package dk.improve.collections
{
    public class Stack
    {
        private var head:StackNode;
        
        public function push(obj:Object):void
        {
            var newNode:StackNode = new StackNode(obj);
            
            if(head == null)
                head = newNode;
            else
            {
                newNode.next = head;
                head = newNode;
            }
        }
        
        public function pop():Object
        {
            if(head != null)
            {
                var result:Object = head.value;
                head = head.next;

                return result;
            }
            else
                return null;
        }
        
        public function peek():Object
        {
            if(head != null)
                return head.value;
            else
                return null;
        }
    }
}

Feedback

Gravatar

Umopepisdn wrote on 5/15/2010 10:51 AM

Thanks, this saved me a couple hours! It's frustrating and surprising to me what AS3 doesn't have. -_-
Gravatar

Sergio Tello wrote on 4/18/2011 10:13 PM

Gracias, realmente es muy buen codigo, y me ayudo muchisimo, saludos.
Gravatar

Francisco Colmenares wrote on 2/3/2012 5:25 PM

Hi Mark,

I'm confused by your implementation, it looks like a Queue instead of a stack. Stacks are LIFO right? But here, it appears that in your structure they are FIFO, that's the definition of a Queue, not a stack.

Still that looks like a very good queue.
Regards,

Francisco.
Gravatar

Mark S. Rasmussen wrote on 2/3/2012 5:58 PM

Francisco,

You're absolutely right, I have no idea how I messed those two up. I've updated the code so it reflects what I meant to write.

Unfortunately I don't have an AS3 compiler with me, so I haven't tested the code. It should work though, I hope :)

- Mark

Post Comment

Name  
Email
Url
Comment
Please add 6 and 4 and type the answer here: