How to create a node for a linked list?
In this Blog post we are going to understand how can one create a node for a linked list, and in the next post we are going to see how we can connect those nodes.
OK Let’s Get started!
I would highly recommend you to first learn about what is attr_accessor in ruby, from one of my blog posts here.
so now if you know what is attr_accessor, just continue to read this story.
First what we need is the skeleton of Node. right?
let’s see how it looks in the code?
class Node
attr_accessor :value, :next
def initialize(value, nex)
@value = value
@next = nex
end
end
In the above code I’ve created a class Node. and created a constructor in the class Node.
so what this will be doing is whenever we will be initialising the object of class Node with some parameters , those parameters will be set in the instance variable @value and @next .
Now we created this class to use it inside another class called LinkedList.
SO let’s see how LinkedList class skeleton looks like in the code:
class LinkedList
attr_accessor :node
def push(value: nil, nex: nil)
@node = Node.new(value, nex)
end
end
Above you can see that we created a class called LinkedList.
And you can see two parts inside the above LinkedList class.
- attr_accessor :node
- instance method push
In the first part we have created a attr_accessor ‘node’ so that we can use it for the linkedlist object.
In the second part we have created a instance method push.
we are going to use method push to the object of LinkedList class.
what is done in the method ‘push’ ?
In the method push we have created a object of Node class, with 2 arguments to it’s constructor value and nex. Which will be creating a Node for us!
And then that node will be returned by the method,
Now?
hmm?
WE JUST LEARNT HOW TO CREATE A NODE FOR A LINKED LIST 🎉🎉
Let’s see how the code looks like
class Node
attr_accessor :value, :next
def initialize(value, nex)
@value = value
@next = nex
end
endclass LinkedList
attr_accessor :node
def push(value: nil, nex: nil)
@node = Node.new(value, nex)
end
end
# Created object of LinkedList
linked_list = LinkedList.new
p linked_list.push(value: 2)
p linked_list.push(value: 1)
Just Copy and Paste the above code in your editor and see it in action.
Thanks for giving it a read!
Stay tuned for the next posts on complete Linked List implementation.
Happy coding!