Posted By

rwitten on 02/11/11


Tagged

stack


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

junaidrao


AS3 Stack


 / Published in: ActionScript 3
 

URL: http://improve.dk/blog/2010/04/20/simple-as3-stack-implementation

Taken from http://improve.dk/blog/2010/04/20/simple-as3-stack-implementation

  1. package dk.improve.collections
  2. {
  3. internal final class StackNode
  4. {
  5. public var value:Object;
  6. public var next:StackNode;
  7.  
  8. public function StackNode(value:Object):void
  9. {
  10. this.value = value;
  11. }
  12. }
  13. }
  14.  
  15. package dk.improve.collections
  16. {
  17. public class Stack
  18. {
  19. private var head:StackNode;
  20. private var tail:StackNode;
  21.  
  22. public function push(obj:Object):void
  23. {
  24. var newNode:StackNode = new StackNode(obj);
  25.  
  26. if(head == null)
  27. head = newNode;
  28. else
  29. tail.next = newNode;
  30.  
  31. tail = newNode;
  32. }
  33.  
  34. public function pop():Object
  35. {
  36. var result:StackNode = head;
  37.  
  38. if(result != null)
  39. {
  40. // If there's no next, the tail should be nulled too as it's == head
  41. if(head.next == null)
  42. tail = null;
  43. head = head.next;
  44.  
  45. return result.value;
  46. }
  47. else
  48. return null;
  49. }
  50.  
  51. public function peek():Object
  52. {
  53. if(head != null)
  54. return head.value;
  55. else
  56. return null;
  57. }
  58. }
  59. }

Report this snippet  

You need to login to post a comment.