[ create a new paste ] login | about

Link: http://codepad.org/iBIWQBeg    [ raw code | output | fork ]

kabhwan - Ruby, pasted on Apr 8:
# C/C++ 로 배우는 자료구조론 연습문제 6.29

class DualStack

  def initialize(size)
    @top_left = -1
    @top_right = size

    @memory = []
    @array_size = size
  end

  def is_full
    return @top_right == @top_left + 1
  end

  def is_empty_left
    return @top_left == -1
  end

  def is_empty_right
    return @top_right == @array_size
  end

  def push_left(data)
    return nil if is_full

    @top_left += 1

    @memory[@top_left] = data
  end

  def push_right(data)
    return nil if is_full

    @top_right -= 1

    @memory[@top_right] = data
  end

  def pop_left
    return nil if is_empty_left

    data = @memory[@top_left]

    @top_left -= 1

    return data
  end

  def pop_right
    return nil if is_empty_right

    data = @memory[@top_right]

    @top_right += 1

    return data
  end

end

stack = DualStack.new(5)
puts stack.push_left(10)
puts stack.push_left(9)
puts stack.push_left(8)
puts stack.push_left(7)
puts stack.push_left(6)
puts stack.push_left(5)
puts stack.push_right(5)
puts stack.is_empty_right
puts stack.pop_left
puts stack.push_right(5)
puts stack.is_full


Output:
1
2
3
4
5
6
7
8
9
10
11
10
9
8
7
6
nil
nil
true
6
5
true


Create a new paste based on this one


Comments: