-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsingly_linked_list.rb
131 lines (105 loc) · 2.11 KB
/
singly_linked_list.rb
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# This file contains the Ruby code from book of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Ruby"
# by Bruno R. Preiss.
#
# Copyright (c) 2004 by Bruno R. Preiss, P.Eng. All rights reserved.
class SinglyLinkedList
class Element
attr_accessor :data, :succ
def initialize(list, data, succ)
@list, @data, @succ = list, data, succ
end
def insert_after(item)
@succ = Element.new(@list, item, @succ)
if @list.tail.equal?(self)
@list.tail = @succ
end
end
def insert_before(item)
tmp = Element.new(@list, item, self)
if @list.head.equal?(self)
@list.head = tmp
else
prevElem = @list.head
while not prevElem.nil? and not prevElem.succ.equal?(self)
prevElem = prevElem.succ
end
prevElem.succ = tmp
end
end
end
attr_accessor :head, :tail
def initialize
@head = nil
@tail = nil
end
def purge
@head = nil
@tail = nil
end
def empty?
@head.nil?
end
def first
if @head.nil?
raise Error
else
@head.data
end
end
def last
if @tail.nil?
raise Error
else
@tail.data
end
end
def prepend(elem)
temp = Element.new(self, elem, @head)
@tail = temp if @head.nil?
@head = temp
end
def append(elem)
temp = Element.new(self, elem, nil)
if @head.nil?
@head = temp
else
@tail.succ = temp
end
@tail = temp
end
def clone
linked_list = SinglyLinkedList.new
elem = @head
while not elem.nil?
linked_list.append elem.data
elem = @head.succ
end
linked_list
end
def extract
elem = @head
prevElem = nil
while not elem.nil? and not elem.data.equal?(item)
prevElem = elem
elem = elem.succ
end
raise ArgumentError if elem.nil?
if elem == @head
@head = elem.succ
else
prevElem.succ = elem.succ
end
if elem == @tail
@tail = prevElem
end
end
def each
elem = @head
while not elem.nil?
yield ptr.data
elem = elem.succ
end
end
end