설명이 필요없는 자료구조... LIFO 만 알아도 구현한다는 그 자료구조!!
그래서, 코드만 적음 'ㅅ'(위키피디아 링크)


# Stack Implementation
# Jungtaek Lim(Heart), 2009-03-03

class Stack

  def initialize(size)
    @top = -1

    @memory = []
    @stack_size = size
  end

  def is_full
    return @top >= (@stack_size - 1)
  end

  def is_empty
    return @top == -1
  end

  def push(data)
    return nil if is_full

    @top += 1

    @memory[@top] = data
  end

  def pop
    return nil if is_empty

    data = @memory[@top]

    @top -= 1

    return data
  end

end

stack = Stack.new(4)

puts stack.push("Data1")
puts stack.push("Data2")
puts stack.push("Data3")
puts stack.push("Data4")
puts stack.push("Data5")

puts stack.pop
puts stack.pop
puts stack.pop
puts stack.pop
puts stack.pop
결과 >
Data1
Data2
Data3
Data4
nil
Data4
Data3
Data2
Data1
nil


크리에이티브 커먼즈 라이선스
Creative Commons License

'Dev.Programming > DS/Algorithm' 카테고리의 다른 글

Circular Queue - in Ruby  (0) 2009/03/04
Queue - in Ruby  (4) 2009/03/04
Stack - in Ruby  (0) 2009/03/03
간단한 문제...(연속된 숫자 그룹 맺어주기)  (0) 2008/09/23
바람개비 별찍기(for 문 2개 이용)  (0) 2008/06/12
자기복제수 문제  (0) 2008/05/23
Posted by Heart