Insert node at beginning of linked list in ruby

Write a program which is create and add new node at the beginning of linked list in ruby.

insert node at beginning of linked list

Here given of code implementation process.

#  Ruby program for
#  Insert node at beginning of linked list

#  Linked list node
class LinkNode 
    # Define the accessor and reader of class LinkNode
    attr_reader :data, :next
    attr_accessor :data, :next
    def initialize(data) 
        self.data = data
        self.next = nil
    end

end

class SingleLL 
    # Define the accessor and reader of class SingleLL
    attr_reader :head
    attr_accessor :head
    def initialize() 
        self.head = nil
    end

    #  Adding new node at beginning of linked list
    def addNode(data) 
        #  Create new node
        node = LinkNode.new(data)
        #  Connect current node to previous head
        node.next = self.head
        self.head = node
    end

    #  Display linked list element
    def display() 
        if (self.head == nil) 
            return
        end

        temp = self.head
        #  iterating linked list elements
        while (temp != nil) 
            print(temp.data ," → ")
            #  Visit to next node
            temp = temp.next
        end

        print(" NULL\n")
    end

end

def main() 
    sll = SingleLL.new()
    #  Linked list
    #  1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → NULL
    sll.addNode(8)
    sll.addNode(7)
    sll.addNode(6)
    sll.addNode(5)
    sll.addNode(4)
    sll.addNode(3)
    sll.addNode(2)
    sll.addNode(1)
    sll.display()
end

main()
 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → NULL

Time complexity of above program is O(1).



Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved