Insert linked list node at nth last position in ruby
Ruby program for Insert linked list node at nth last position. Here problem description and explanation.
# Ruby program for
# Insert linked list node at nth last position
# 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 LinkedList
# Define the accessor and reader of class LinkedList
attr_reader :head
attr_accessor :head
def initialize()
self.head = nil
end
# insert node at end position
def insert(value)
# Create a new node
node = LinkNode.new(value)
if (self.head == nil)
self.head = node
else
temp = self.head
# Find the last node
while (temp.next != nil)
# Visit to next node
temp = temp.next
end
# Add node
temp.next = node
end
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
# Add node at specific position from the end of linked list
def endPosition(position, value)
if (self.head == nil)
print("Empty Linked list", "\n")
elsif (position <= 0)
print("Invalid position", "\n")
else
temp = self.head
location = nil
while (temp != nil)
position -= 1
if (position <= 0)
if (location == nil)
location = self.head
else
location = location.next
end
end
# visit to next node
temp = temp.next
end
if (position <= 1)
node = LinkNode.new(value)
if (location == nil)
# Add node at first place
node.next = self.head
self.head = node
else
# Add node at intermediate position
node.next = location.next
location.next = node
end
else
print("Opps position not found", "\n")
end
end
end
end
def main()
sll = LinkedList.new()
# Add node
sll.insert(5)
sll.insert(4)
sll.insert(3)
sll.insert(2)
sll.insert(1)
sll.display()
position = 2
data = 10
sll.endPosition(position, data)
print(" Add ", data ," at last ",
position ,"-nd position", "\n")
sll.display()
end
main()
Output
5 → 4 → 3 → 2 → 1 → NULL
Add 10 at last 2-nd position
5 → 4 → 3 → 2 → 10 → 1 → NULL
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