Archive for October, 2010

Create a Stack / Queue Data Structure in Flex / Actionscript

October 3, 2010

We may require to do operations in our applications, like ‘Undo / Redo’. We can easily achieve this by using a data structures like Stack, queue, etc. In the Undo/Redo operation we can use a stack to accomplish. I am going to explain how we can create a linked stack and linked queue.

We need two classes. One to denote each Nodes of the stack / queue and the next class to implement the stack or queue.

First we will look at the node class. I am naming it as Node.as :

package dataStore{
public class Node{
public var next : dataStore.Node;
public var data : Object;
}
}
I declared two variables : one for storing the data and the other for storing the next object. This class am putting under the package named : dataStore.
Now, we have created the nodes, now its the time to arrange these nodes in a structure. First we will see how to make the stack. I am naming it as Stack.as :

package dataStore{
public class Stack{
private var first:Node;
public function isEmpty ():Boolean{
return first == null;
}
public function push (data : Object):void{
var oldFirst : Node = first;
first = new Node ();
first.data = data;
first.next = oldFirst;
}
public function pop () : Object{
if (isEmpty ()){
return null; //if stack has no data inside that, you can handle it here
}
var data:Object = first.data;
first = first.next;
return data;
}
}
}
We can now move on to queue. Queue.as :
package dataStore;

public class Queue {
private var first:Node;
private var last:Node;
public function isEmpty():Boolean{
return (first == null);
}
public function push(data:Object):void{
var node:Node = new Node();
node.data = data;
node.next = null;
if (isEmpty()) {
first = node;
last = node;
} else {
last.next = node;
last = node;
}
}
public function pop():Object{
if (isEmpty()) {
return null; //if stack has no data inside that, you can handle it here
}
var data = first.data;
first = first.next;
return data;
}
}
These two classes can be used directly in your application. Declare one variable of these classes and call the push and pop functions accordingly. That’s it…
Happy Coding Guyzz 🙂

Advertisements

%d bloggers like this: