Ruby Programming Tutorial - Lesson 31 - Doubly Linked list by bilal-haider

View this thread on steempeak.com
· @bilal-haider ·
$6.76
Ruby Programming Tutorial - Lesson 31 - Doubly Linked list
![doubly-linked-list.gif](https://steemitimages.com/DQmeoxdQSdCL6CBCk58R3iRXmYrpok29JecBH7bjUU3TiR2/doubly-linked-list.gif)

# Doubly Linked list 

In previous article, we learned to create singly linked list, every node in singly linked list has in it the information of next node. but it does not have information about previous node.. 
Which makes traversal go from head to tail direction and not backwards. 

e.g We can not start from tail and go back to head.. that kind of exploration of nodes is not possible with singly linked list

### Doubly list
> doubly linked list is a data structure, which consists upon nodes linked together in a way that every node contains reference to its both neighbor nodes (e.g previous and next), which makes it possible to traverse the list in both ways, backwards and forward

Lets start by creating a Node 

```
class Node
    attr_accessor :val, :next, :prev
  
    def initialize(prev_node, val, next_node)
        @prev = prev_node
        @val  = val
        @next = next_node
    end
end
```
![Screenshot from 2018-03-21 08-55-39.png](https://steemitimages.com/DQmWzyPZzvCoSxpmhF9RbXQzZJLwhsdXckQQXTX7LCXxd7a/Screenshot%20from%202018-03-21%2008-55-39.png)

Once we have the node, we can start changing our singly list's code to convert into doubly list .. 
notice that doubly list allows us to add few more methods

- We can add a new node at the tip of chain
- We can add a new node at the tail of chain
- We can add a new add at any random local of the chain 
- We can traverse the chain from head to tail, and from tail back to head
- we can go forward and backward at any node 

![Screenshot from 2018-03-21 09-33-30.png](https://steemitimages.com/DQmQrtVVruADMfRdPuVoffgwquZqXjdEpo2pkwhRmHk38wp/Screenshot%20from%202018-03-21%2009-33-30.png)
![Screenshot from 2018-03-21 09-33-50.png](https://steemitimages.com/DQmb8kF5FXDkYREt5us3qEwYCwXXHhF4SXKuajttidnbMkb/Screenshot%20from%202018-03-21%2009-33-50.png)

Here is the code

```
require_relative 'node'

class DoublyList
    def initialize(val)
        @head = Node.new(nil, val, nil)
        puts @head.val
    end
    
    def add_to_tail(val)
        current = @head
        while current.next != nil
          current = current.next
        end
        current.next = Node.new(current, val, nil)
    end
    def add_to_tip(val)
        current           = @head
        new_node          = Node.new(current, val, current.next)
        current.next.prev = new_node
        current.next = new_node
    end
    def return_list
        elements = []
        current = @head
        while current.next != nil
          elements << current
          current = current.next
        end
        elements << current
    end
  
    def display_list
        puts "Going from Head to Tail"
        current = @head
        while current.next != nil
            puts current.val
            current = current.next
        end
        puts current.val

        puts "Going from Tail to Head"
        while current.prev != nil
            puts current.val
            current = current.prev
        end
        puts current.val
    end
end
```

Notice that I did not created method to add in the middle of the list. but you can implement the method to do so, 
we can add a data member called :id that is similar to blockchain's height variable. 
but you can add a floating number, so when you need to add a node in the middle of chain. you can add it 
based upon height .. and change the height of new node to 2.1 which can be added between 2 and 3 height nodes

## Now lets see how we coded main.rb program to use this list 

```
require_relative 'doublylist'

_data = {username: "bilalhaider", age: "27", salary: 0.00, reward: 50}
puts "Genesis Node Data: #{_data}"

_mylist = DoublyList.new(_data)

while $entry.to_i != 5
    print "1 - Insert new at Tail\n2 - Insert new data at Tip\n3 - Display List\n4 - Return List\n5 - Exit\n Your Choice: "
    $entry = gets.chomp 

    if $entry.to_i == 1
        print "Insert your Name: "
        _username = gets.chomp
        
        print "Insert your age: "
        _age      = gets.chomp
        
        print "Insert your salary: "
        _salary   = gets.chomp
        _data = {username: _username, age: _age, salary: _salary, reward: 50}
        puts "Data Inserted at Tail: #{_data}"

        _mylist.add_to_tail(_data)
    elsif $entry.to_i == 2
        print "Insert your Name: "
        _username = gets.chomp
        
        print "Insert your age: "
        _age      = gets.chomp
        
        print "Insert your salary: "
        _salary   = gets.chomp
        _data = {username: _username, age: _age, salary: _salary, reward: 50}
        puts "Data Inserted at Tip: #{_data}"

        _mylist.add_to_tip(_data)
    elsif $entry.to_i == 3
        puts _mylist.display_list
    elsif $entry.to_i == 4
        puts _mylist.return_list
    elsif $entry.to_i == 5 
        puts "Exiting .... "
    else 
        puts "Invalid choice "
    end
end
```
Finally when we execute our program, we have 5 options to choose from .. 
Notice that our chain is fully intact.. 

![Screenshot from 2018-03-21 09-38-54.png](https://steemitimages.com/DQmbca2ErY11nS6unjKe2odNbT19a98292WUtXA2fKJQgV9/Screenshot%20from%202018-03-21%2009-38-54.png)

Its difficult to explain all the methods one by one.

### Couple of notes

- When adding a node to the tip of chain, first we need to get reference of @head node.
   - Create a new node, and update references so that its connected to the chain
   - Update the head's next node to new_node,  new_node's previous to head's node, new_node's next to @head's next
   - and finally the next's node's previous to new_node's .. 
   - That way node is successfully added to the chain, and its connected perfectly 

- When adding a node to tail is less tricky, you traverse the list until tail is reached. then create a new node
   - New node's previous should be set to last node , and last node's next should be set to new node
   - Finally new node's next should be nil , as there is no next node ..

This data structure can come handy when building a blockchain which allows to insert nodes at any height :)
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
properties (23)
post_id39,716,464
authorbilal-haider
permlinkruby-programming-tutorial-lesson-31-doubly-linked-list
categoryruby
json_metadata"{"app": "steemit/0.1", "format": "markdown", "users": ["head"], "image": ["https://steemitimages.com/DQmeoxdQSdCL6CBCk58R3iRXmYrpok29JecBH7bjUU3TiR2/doubly-linked-list.gif"], "tags": ["ruby", "programming", "steem", "steemit", "dev"]}"
created2018-03-21 04:53:33
last_update2018-03-21 04:53:33
depth0
children11
net_rshares2,144,406,583,602
last_payout2018-03-28 04:53:33
cashout_time1969-12-31 23:59:59
total_payout_value5.662 SBD
curator_payout_value1.093 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length6,188
author_reputation4,774,071,168,640
root_title"Ruby Programming Tutorial - Lesson 31 - Doubly Linked list"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
author_curate_reward""
vote details (42)
@minnows-freedom ·
Wow! This is great content! You have received a free upvote from the <em>Minnows Freedom Project</em> for being a good Steemian and posting original content. To learn more about us or to support us, please visit @minnows-freedom. You can also find us on [Discord](https://discord.gg/Ce7J3qe). Stay cool, create good content and have a nice day!
properties (22)
post_id39,719,268
authorminnows-freedom
permlinkre-ruby-programming-tutorial-lesson-31-doubly-linked-list-20180321t051837
categoryruby
json_metadata"{"app": "piston-lib/0.5.7"}"
created2018-03-21 05:18:36
last_update2018-03-21 05:18:36
depth1
children0
net_rshares0
last_payout2018-03-28 05:18:36
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length344
author_reputation2,137,962,089
root_title"Ruby Programming Tutorial - Lesson 31 - Doubly Linked list"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@soumit420 ·
plz upvote comment & follow
properties (22)
post_id39,723,473
authorsoumit420
permlinkre-bilal-haider-ruby-programming-tutorial-lesson-31-doubly-linked-list-20180321t055727307z
categoryruby
json_metadata"{"app": "steemit/0.1", "tags": ["ruby"]}"
created2018-03-21 05:57:30
last_update2018-03-21 05:57:30
depth1
children0
net_rshares0
last_payout2018-03-28 05:57:30
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length27
author_reputation-7,451,131,400
root_title"Ruby Programming Tutorial - Lesson 31 - Doubly Linked list"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@dearkafka ·
When the RPG maker boom was strong in Youtube, i was very interested in Ruby on Rails, since it was the language the program used, and while i never ultimately pursued that interest, your videos definitely make it so understanding the basics of this language seem more accessible for beginners like me. Thank you :)
👍  
properties (23)
post_id39,755,222
authordearkafka
permlinkre-bilal-haider-ruby-programming-tutorial-lesson-31-doubly-linked-list-20180321t103649580z
categoryruby
json_metadata"{"app": "steemit/0.1", "tags": ["ruby"]}"
created2018-03-21 10:36:51
last_update2018-03-21 10:36:51
depth1
children1
net_rshares2,037,096,624
last_payout2018-03-28 10:36:51
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length315
author_reputation0
root_title"Ruby Programming Tutorial - Lesson 31 - Doubly Linked list"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
author_curate_reward""
vote details (1)
@bilal-haider ·
Hopefully you will become an awesome ruby programmer in future :) I will continue publishing more material ..
properties (22)
post_id39,757,218
authorbilal-haider
permlinkre-dearkafka-re-bilal-haider-ruby-programming-tutorial-lesson-31-doubly-linked-list-20180321t105338436z
categoryruby
json_metadata"{"app": "steemit/0.1", "tags": ["ruby"]}"
created2018-03-21 10:53:39
last_update2018-03-21 10:53:39
depth2
children0
net_rshares0
last_payout2018-03-28 10:53:39
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length109
author_reputation4,774,071,168,640
root_title"Ruby Programming Tutorial - Lesson 31 - Doubly Linked list"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@bamsbrayen ·
@bilal-haider You are a programmer!
can you detect someone who has hacked someone's steemit. because there is my friend who was hit by his steemit hack.
properties (22)
post_id39,765,982
authorbamsbrayen
permlinkre-bilal-haider-ruby-programming-tutorial-lesson-31-doubly-linked-list-20180321t120052976z
categoryruby
json_metadata"{"app": "steemit/0.1", "users": ["bilal-haider"], "tags": ["ruby"]}"
created2018-03-21 12:00:57
last_update2018-03-21 12:00:57
depth1
children3
net_rshares0
last_payout2018-03-28 12:00:57
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length152
author_reputation3,920,426,655
root_title"Ruby Programming Tutorial - Lesson 31 - Doubly Linked list"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@bilal-haider · (edited)
I can't, my own account @bilalhaider was hacked :D :p
properties (22)
post_id39,766,231
authorbilal-haider
permlinkre-bamsbrayen-re-bilal-haider-ruby-programming-tutorial-lesson-31-doubly-linked-list-20180321t120249202z
categoryruby
json_metadata"{"app": "steemit/0.1", "users": ["bilalhaider"], "tags": ["ruby"]}"
created2018-03-21 12:02:51
last_update2018-03-21 12:03:21
depth2
children2
net_rshares0
last_payout2018-03-28 12:02:51
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length53
author_reputation4,774,071,168,640
root_title"Ruby Programming Tutorial - Lesson 31 - Doubly Linked list"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@bamsbrayen ·
Ok, thank you
but if you get the answer to my question please inform me. ok
properties (22)
post_id39,768,419
authorbamsbrayen
permlinkre-bilal-haider-re-bamsbrayen-re-bilal-haider-ruby-programming-tutorial-lesson-31-doubly-linked-list-20180321t121922350z
categoryruby
json_metadata"{"app": "steemit/0.1", "tags": ["ruby"]}"
created2018-03-21 12:19:27
last_update2018-03-21 12:19:27
depth3
children1
net_rshares0
last_payout2018-03-28 12:19:27
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length75
author_reputation3,920,426,655
root_title"Ruby Programming Tutorial - Lesson 31 - Doubly Linked list"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@prpeuufj ·
Good job brother:)
properties (22)
post_id39,769,669
authorprpeuufj
permlinkre-bilal-haider-2018321t192911682z
categoryruby
json_metadata"{"app": "esteem/1.5.1", "format": "markdown+html", "community": "esteem", "tags": ["ruby", "programming", "steem", "steemit", "dev"]}"
created2018-03-21 12:29:36
last_update2018-03-21 12:29:36
depth1
children1
net_rshares0
last_payout2018-03-28 12:29:36
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length18
author_reputation10,880,946,292
root_title"Ruby Programming Tutorial - Lesson 31 - Doubly Linked list"
beneficiaries
0.
accountesteemapp
weight1,000
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@bilal-haider ·
glad you like it :) <3
properties (22)
post_id39,769,966
authorbilal-haider
permlinkre-prpeuufj-re-bilal-haider-2018321t192911682z-20180321t123140452z
categoryruby
json_metadata"{"app": "steemit/0.1", "tags": ["ruby"]}"
created2018-03-21 12:31:42
last_update2018-03-21 12:31:42
depth2
children0
net_rshares0
last_payout2018-03-28 12:31:42
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length22
author_reputation4,774,071,168,640
root_title"Ruby Programming Tutorial - Lesson 31 - Doubly Linked list"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@rianh ·
Please votes me and follow
properties (22)
post_id39,800,287
authorrianh
permlinkre-bilal-haider-2018321t225221908z
categoryruby
json_metadata"{"app": "esteem/1.5.1", "format": "markdown+html", "community": "esteem", "tags": ["ruby", "programming", "steem", "steemit", "dev"]}"
created2018-03-21 15:52:39
last_update2018-03-21 15:52:39
depth1
children0
net_rshares0
last_payout2018-03-28 15:52:39
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length26
author_reputation2,148,929,769
root_title"Ruby Programming Tutorial - Lesson 31 - Doubly Linked list"
beneficiaries
0.
accountesteemapp
weight1,000
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000