diff options
| author | mo khan <mo.khan@gmail.com> | 2020-08-15 10:57:40 -0600 |
|---|---|---|
| committer | mo khan <mo.khan@gmail.com> | 2020-08-15 10:57:40 -0600 |
| commit | bc99703e96daae080a3a075224b70bf47e34a90e (patch) | |
| tree | 5239107a4ecdf863f7f0bbd5902531749ea9b323 /2020 | |
| parent | 5143fd22d32aad6f5c93f044b996806aadc3df59 (diff) | |
Complete iterative solution
Diffstat (limited to '2020')
| -rw-r--r-- | 2020/08/15/README.md | 2 | ||||
| -rw-r--r-- | 2020/08/15/main.rb | 91 |
2 files changed, 91 insertions, 2 deletions
diff --git a/2020/08/15/README.md b/2020/08/15/README.md index c4df310..406b6e1 100644 --- a/2020/08/15/README.md +++ b/2020/08/15/README.md @@ -43,5 +43,3 @@ │print("List after reversal: ") │testTail.printList() │# 0 1 2 3 4 - - diff --git a/2020/08/15/main.rb b/2020/08/15/main.rb new file mode 100644 index 0000000..2e7121d --- /dev/null +++ b/2020/08/15/main.rb @@ -0,0 +1,91 @@ +def assert_equals(x, y) + raise [x, y].inspect unless x == y +end + +class ListNode + attr_accessor :data, :next + + def initialize(data) + @data = data + @next = nil + end + + def to_a + current = self + items = [] + while current + items << current.data + current = current.next + end + items + end + + def inspect + print "[" + to_a.each { |current| print "(#{current})->" } + puts "(nil)]" + end + + def to_s + data.to_s + end +end + +class Solution + def self.run(head) + stack = [] + current = head + + while current + stack.push(current) + current = current.next + end + + until stack.empty? + c = stack.pop + n = stack[-1] + c.next = n + end + end +end + +=begin +[(4)->(3)->(2)->(1)->(0)->(nil)] + +list + + n c t +[(nil)<-(4)<-(3)<-(2)<-(1)<-(0) (nil)] + +# stack + + c + n +|0|1|2|3|4| + +until stack.empty? + c = stack.pop + n = stack.peek + t = c.next + + c.next = n +end + +=end + +head = ListNode.new(4) +node1 = ListNode.new(3) +node2 = ListNode.new(2) +node3 = ListNode.new(1) +tail = ListNode.new(0) + +head.next = node1 +node1.next = node2 +node2.next = node3 +node3.next = tail + +puts head.inspect +assert_equals(head.to_a, [4,3,2,1,0]) +Solution.run(head) +puts tail.inspect +assert_equals(tail.to_a, [0,1,2,3,4]) |
