Mark S. Rasmussen improve.dk
Apr 21
2010

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;
        }
    }
}
Mark S. Rasmussen
I'm the CTO at iPaper where I cuddle with databases, mold code and maintain the overall technical & team responsibility. I'm an avid speaker at user groups & conferences. I love life, motorcycles, photography and all things technical. Say hi on Twitter, write me an email or look me up on LinkedIn.