Class: LinkedList

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/prct11/linkedList.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeLinkedList

Returns a new instance of LinkedList.



6
7
8
9
10
# File 'lib/prct11/linkedList.rb', line 6

def initialize()
	@Node = Struct.new(:value, :next, :prev)
	@head = nil
	@tail = nil
end

Instance Attribute Details

#nodeObject

Returns the value of attribute node.



4
5
6
# File 'lib/prct11/linkedList.rb', line 4

def node
  @node
end

Instance Method Details

#eachObject



87
88
89
90
91
92
93
# File 'lib/prct11/linkedList.rb', line 87

def each
	iterator = @head
	while !iterator.nil?
	    yield iterator[:value]
		iterator = iterator[:next]
	end
end

#extract_by_beginObject



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/prct11/linkedList.rb', line 32

def extract_by_begin()
	if @head.nil?
		raise RuntimeError, "List is empty, you can't extract a node"
	else
		if @head == @tail
			@head, @tail = nil
		else
			@head = @head[:next]
			@head[:prev] = nil
		end
		@head[:value]
	end
end

#extract_by_endObject



46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/prct11/linkedList.rb', line 46

def extract_by_end()
	if @head.nil?
		raise RuntimeError, "List is empty, you can't extract a node"
	else 
		if @head == @tail
			@head, @tail = nil
		else
			@tail = @tail[:prev]
			@tail[:next] = nil
		end
	end
end

#get_nextObject



63
64
65
# File 'lib/prct11/linkedList.rb', line 63

def get_next
    return @head[:next]
end

#get_prevObject



67
68
69
# File 'lib/prct11/linkedList.rb', line 67

def get_prev
    return @head[:prev]
end

#get_valueObject



59
60
61
# File 'lib/prct11/linkedList.rb', line 59

def get_value
	return @head[:value]
end

#insert_by_begin(value) ⇒ Object



12
13
14
15
16
17
18
19
20
# File 'lib/prct11/linkedList.rb', line 12

def insert_by_begin(value)
	if @head.nil?
		@head = @Node.new(value, nil, nil)
		@tail = @head
	else
		@head[:prev] = @Node.new(value, @head, nil)
		@head = @head[:prev]
	end
end

#insert_by_end(value) ⇒ Object



22
23
24
25
26
27
28
29
30
# File 'lib/prct11/linkedList.rb', line 22

def insert_by_end(value)
	if @head.nil?
		@head = @Node.new(value, nil, nil)
		@tail = @head
	else
		@tail[:next] = @Node.new(value, nil, @tail)
		@tail = @tail[:next]
	end
end

#insert_set(others) ⇒ Object



81
82
83
84
85
# File 'lib/prct11/linkedList.rb', line 81

def insert_set(others)
    for i in (0.. others.size-1)
        insert_by_end(others[i])
    end
end

#sizeObject



71
72
73
74
75
76
77
78
79
# File 'lib/prct11/linkedList.rb', line 71

def size
	size = 0
	iterator = @head
	while (!iterator.nil?)
		iterator = iterator[:next]
		size+=1
	end
	return size
end