Flatten a folded linked list in ruby
Ruby program for Flatten a folded linked list. Here problem description and other solutions.
# Ruby program for
# Unfold a folded linked list OR
# flatten folded 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
# Insert node at the beginning of linked list
def addNode(data)
# Create node
node = LinkNode.new(data)
node.next = self.head
# Set new 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
# This is handle the request of unfold given linked list nodes
def unfoldList()
if (self.head == nil)
print("\n Empty linked list\n")
return
end
temp = self.head
auxiliary = nil
hold = nil
# Loop which is separating the fold elements
while (temp.next != nil)
# Get the second element
hold = temp.next
if (hold.next != nil)
# When exists pair of three elements
temp.next = hold.next
# Visit to 3rd element
temp = hold.next
else
# When get last two elements
temp.next = nil
end
# Add new node at beginning of auxiliary linked list
hold.next = auxiliary
# Make new head node
auxiliary = hold
end
if (temp != nil)
# Combine lists
temp.next = auxiliary
end
end
end
def main()
# Create a empty linked lists
sll1 = SingleLL.new()
sll2 = SingleLL.new()
# Constructed first linked list
# 2 → 5 → 1 → 8 → 10 → 4 → 9 → 7 → NULL
sll1.addNode(7)
sll1.addNode(9)
sll1.addNode(4)
sll1.addNode(10)
sll1.addNode(8)
sll1.addNode(1)
sll1.addNode(5)
sll1.addNode(2)
# Constructed second linked list
# 1 → 2 → 3 → 4 → 5 → 6 → 7 → NULL
sll2.addNode(7)
sll2.addNode(6)
sll2.addNode(5)
sll2.addNode(4)
sll2.addNode(3)
sll2.addNode(2)
sll2.addNode(1)
# Test A
print(" Before unfold\n")
sll1.display()
sll1.unfoldList()
print(" After unfold\n")
sll1.display()
# Test B
print(" Before unfold\n")
sll2.display()
sll2.unfoldList()
print(" After unfold\n")
sll2.display()
end
main()
Output
Before unfold
2 → 5 → 1 → 8 → 10 → 4 → 9 → 7 → NULL
After unfold
2 → 1 → 10 → 9 → 7 → 4 → 8 → 5 → NULL
Before unfold
1 → 2 → 3 → 4 → 5 → 6 → 7 → NULL
After unfold
1 → 3 → 5 → 7 → 6 → 4 → 2 → 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