Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b11b665

Browse files
exercism 77 Simple linked List
1 parent 7cfc0fd commit b11b665

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,7 @@ solution of many challenges of [Leetcode](https://leetcode.com/), [Exercism](htt
298298
74. [Atbash Cipher](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/atbash_cipher.rb)
299299
75. [Crypto Square](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/crypto_square.rb)
300300
76. [List Ops](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/list_ops.rb)
301+
77. [Simple Linked List](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/simple_linked_list.rb)
301302

302303
<a name="leetcode"/>
303304

‎exercism/simple_linked_list.rb‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# Problem : https://exercism.org/tracks/ruby/exercises/simple-linked-list
2+
3+
# Solution
4+
class Element
5+
attr_accessor :next,:datum
6+
def initialize(data)
7+
@datum = data
8+
@next = nil
9+
end
10+
end
11+
12+
class SimpleLinkedList
13+
def initialize(elements=[])
14+
@head = nil
15+
elements.each do |element|
16+
push(Element.new(element))
17+
end
18+
end
19+
20+
def push(element)
21+
if @head.nil?
22+
@head = element
23+
else
24+
tail = find_tail
25+
tail.next = element
26+
end
27+
self
28+
end
29+
30+
def pop
31+
current = @head
32+
if @head.nil? or @head.next.nil?
33+
@head = nil
34+
return current
35+
end
36+
current = current.next until current.next.next.nil?
37+
last_node = current.next
38+
current.next = nil
39+
last_node
40+
end
41+
42+
def to_a
43+
current = @head
44+
data = []
45+
until current.nil?
46+
data.push(current.datum)
47+
current = current.next
48+
end
49+
data.reverse
50+
end
51+
52+
def reverse!
53+
current = @head
54+
prev = nil
55+
until current.nil?
56+
next_node = current.next
57+
current.next = prev
58+
prev = current
59+
current = next_node
60+
end
61+
@head = prev
62+
self
63+
end
64+
65+
private
66+
def find_tail
67+
node = @head
68+
node = node.next until node.next.nil?
69+
node
70+
end
71+
end

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /