aboutsummaryrefslogtreecommitdiffstats
path: root/sample/list.rb
blob: 76035e67d6504cc3d37cf7fbeec13fdec45fba2c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# Linked list example
class MyElem
  # ���֥��������������˼�ưŪ�˸ƤФ��᥽�å�
  def initialize(item)
    # @�ѿ��ϥ��󥹥����ѿ�(������פ�ʤ�)
    @data = item
    @succ = nil
  end

  def data
    @data
  end

  def succ
    @succ
  end

  # ��obj.data = val�פȤ����Ȥ��˰��ۤ˸ƤФ��᥽�å�
  def succ=(new)
    @succ = new
  end
end

class MyList
  def add_to_list(obj)
    elt = MyElem.new(obj)
    if @head
      @tail.succ = elt
    else
      @head = elt
    end
    @tail = elt
  end

  def each
    elt = @head
    while elt
      yield elt
      elt = elt.succ
    end
  end

  # ���֥������Ȥ�ʸ������Ѵ�����᥽�å�
  # ��������������print�Ǥ�ɽ�����Ѥ��
  def to_s
    str = "<MyList:\n";
    for elt in self
      # ��str = str + elt.data.to_s + "\n"�פξ�ά��
      str += elt.data.to_s + "\n"
    end
    str += ">"
    str
  end
end

class Point
  def initialize(x, y)
    @x = x; @y = y
    self
  end

  def to_s
    sprintf("%d@%d", @x, @y)
  end
end

# ����ѿ���`$'�ǻϤޤ롥
$list1 = MyList.new
$list1.add_to_list(10)
$list1.add_to_list(20)
$list1.add_to_list(Point.new(2, 3))
$list1.add_to_list(Point.new(4, 5))
$list2 = MyList.new
$list2.add_to_list(20)
$list2.add_to_list(Point.new(4, 5))
$list2.add_to_list($list1)

# ۣ��Ǥʤ��¤�᥽�åɸƤӽФ��γ�̤Ͼ�ά�Ǥ���
print "list1:\n", $list1, "\n"
print "list2:\n", $list2, "\n"