[Flash] Stack & Queue

  • Stack & Queue
  • 雖然Flash本身並沒有提供Stack這類的Class,但是事實上你可以直接使用Array Class的pop(), push(), shift()來達到Stack or Queue的效果。這裡我則是不使用Array Class來實做。上面的範例只是小小的展示Stack(FILO)跟Queue(FIFO)的性質。

    下面程式碼是依造Stack/Queue Implemented Linked Structures這一篇所修改而來的。

    /* Node.as */
    package com.xinyu.collection{
    public class Node {
    public var next:Node = null;
    public var data:Object = null;

    public function Node(data:Object = null, next:Node = null){
    this.data = data;
    this.next = next;
    }
    }
    }

    /* Stack.as */
    package com.xinyu.collection{
    import com.xinyu.collection.Node;
    public class Stack {
    private var _top:Node;
    private var _length:Number;

    public function Stack(){
    _top = null;
    _length = 0;
    }

    public function isEmpty():Boolean {
    return _top == null;
    }

    public function push(data : Object):void {
    var newTop:Node = new Node(data, _top);
    _top = newTop;
    _length += 1;
    }

    public function pop():Object {
    if (isEmpty ()) {
    return "empty";
    }

    _length -= 1;
    var data:Object = _top.data;
    _top = _top.next;
    return data;
    }

    public function peek():Object {
    if (isEmpty ()) {
    return "empty";
    }
    return _top.data;
    }

    public function get length():Number{
    return _length;
    }
    }
    }

    /* Queue */
    package com.xinyu.collection{
    import com.xinyu.collection.Node;

    public class Queue {
    private var _bottom:Node;
    private var _top:Node;
    private var _length:Number;

    public function Queue(){
    _bottom = _top = null;
    _length = 0;
    }

    public function isEmpty():Boolean {
    return (_bottom == null);
    }

    public function enqueue(data:Object):void {
    var node:Node = new Node(data, null);
    if (isEmpty()) {
    _bottom = node;
    _top = node;
    } else {
    _top.next = node;
    _top = node;
    }
    _length += 1;
    }

    public function dequeue():Object{
    if (isEmpty()) {
    return "empty";
    }

    _length -= 1;
    var data:Object = _bottom.data;
    _bottom = _bottom.next;
    return data;
    }

    public function peek():Object {
    if (isEmpty()) {
    return "empty";
    }

    return _bottom.data;
    }

    public function get length():Number{
    return _length;
    }
    }
    }

    正常來說Stack跟Queue是不需要在意length的問題(前提是不考慮記憶體大小以及程式本身的Stack Size 等限制),而這裡我卻加了一個length變數,目的只是想要知道目前存了多少個元素(有點像ArrayCollection),當然上面的寫法是一種很簡易的實做,並沒有去限定Stack/Queue本身儲存的Data type一致的問題(也就是說Number, String, Boolean...等各種型態皆可放置在上面的 Stack/Queue裡),所以在設計時要格外注意一下型態的問題。(由於StackQueueDemo.mxml只是單純展示Stack/Queue用的,並沒有實質的意義,所以就不貼出了)

No comments:

Post a Comment

Orange - data analysis tool

Installation pip install orange3 Run orange python -m Orange.canvas