Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

fifo

  • Loading branch information...
commit a8f118fbd4bbc202163f8be0c7380c5c61a45e1f 1 parent 7dbccde
David Kasper authored January 27, 2012

Showing 1 changed file with 54 additions and 0 deletions. Show diff stats Hide diff stats

  1. 54  queue.rb
54  queue.rb
... ...
@@ -0,0 +1,54 @@
  1
+class Node
  2
+  attr_accessor :value, :next
  3
+end
  4
+
  5
+class Fifo
  6
+  def initialize
  7
+    @head = nil
  8
+    @tail = nil
  9
+  end
  10
+
  11
+  def enqueue(v)
  12
+    n = Node.new
  13
+    n.value = v
  14
+    if @tail.nil? || @head.nil?
  15
+      @head = n
  16
+      @tail = n
  17
+    else
  18
+      @tail.next = n
  19
+      @tail = n
  20
+    end
  21
+  end
  22
+
  23
+  def dequeue
  24
+    return nil unless @head
  25
+    oldhead = @head
  26
+    @head = oldhead.next
  27
+    oldhead.value
  28
+  end
  29
+end
  30
+
  31
+describe Fifo, 'queue' do
  32
+  it "should enqueue-dequeue" do
  33
+    f = Fifo.new
  34
+    f.enqueue(1)
  35
+    f.dequeue.should == 1
  36
+  end
  37
+
  38
+  it "should enqueue-dequeue multiple" do
  39
+    f = Fifo.new
  40
+    f.enqueue(1)
  41
+    f.enqueue(2)
  42
+    f.enqueue(3)
  43
+    f.dequeue.should == 1
  44
+    f.dequeue.should == 2
  45
+    f.dequeue.should == 3
  46
+    f.enqueue(4)
  47
+    f.dequeue.should == 4
  48
+  end
  49
+
  50
+  it "should be nil on empty dequeue" do
  51
+    f = Fifo.new
  52
+    f.dequeue.nil?.should == true
  53
+  end
  54
+end

0 notes on commit a8f118f

Please sign in to comment.
Something went wrong with that request. Please try again.