Skip to content

Commit 3729c89

Browse files
committed
exercism 82 Linked List
1 parent e9bf20a commit 3729c89

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,7 @@ solution of many challenges of [Leetcode](https://leetcode.com/), [Exercism](htt
307307
79. [Rotational Cipher](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/rotational_cipher.rb)
308308
80. [Largest Series Product](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/largest_series_product.rb)
309309
81. [Prime Factors](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/prime_factors.rb)
310+
82. [Linked List](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/linked_list.rb)
310311

311312
<a name="leetcode"/>
312313

exercism/linked_list.rb

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Problem : https://exercism.org/tracks/ruby/exercises/linked-list
2+
3+
#Solution
4+
class Deque
5+
NODE = Struct.new(:val,:prev,:next)
6+
7+
def initialize
8+
@head = nil
9+
@tail = @head
10+
end
11+
12+
def push(element)
13+
if @tail.nil?
14+
@head = @tail = NODE.new(element,nil,nil)
15+
return
16+
end
17+
last_node = @tail
18+
last_node.next = NODE.new(element,last_node,nil)
19+
@tail = last_node.next
20+
end
21+
def pop
22+
23+
unless @tail.nil?
24+
last_node = @tail
25+
@tail = @tail.prev
26+
return last_node.val
27+
end
28+
end
29+
30+
def shift
31+
first_val = @head.val
32+
@head = @head.next
33+
@tail = nil if @head.nil?
34+
first_val
35+
end
36+
37+
def unshift(element)
38+
new_node = NODE.new(element, nil, @head)
39+
@head.prev = new_node unless @head.nil?
40+
@head = new_node
41+
@tail = new_node if @tail.nil?
42+
end
43+
end
44+
45+
# Solution (one liner)
46+
class Deque < Array; end # As array class has all the functionalities in Ruby

0 commit comments

Comments
 (0)