# Convert a doubly linked list into spiral form in ruby

Ruby program for Convert a doubly linked list into spiral form. Here problem description and other solutions.

#  Ruby program for
#  Convert a doubly linked list spiral form
attr_accessor :data, :next, :prev
def initialize(data)
self.data = data
self.next = nil
self.prev = nil
end

end

def initialize()
self.tail = nil
end

#  Insert new node at end position
def insert(value)
#  Create a node
self.tail = node
return
end

#  Add node at last position
self.tail.next = node
node.prev = self.tail
self.tail = node
end

#  Display node element of doubly linked list
def display()
else

#  Get first node of linked list
while (temp != nil)
#  Display node value
print("  ", temp.data)
#  Visit to next node
temp = temp.next
end

#  Get last node of linked list
temp = self.tail
while (temp != nil)
#  Display node value
print("  ", temp.data)
#  Visit to prev node
temp = temp.prev
end

end

end

#   Converting a doubly linked list into spiral form
def spiral()
return
end

#  Auxiliary variables
auxiliary = nil
temp = nil
#  spiral view is combination first and last node
#  Example 1 2 3 4 5
#          1       5  [Get corner nodes]
#                     [1,4] result
#            2 3 4
#            2   4    [Get corner nodes]
#                     [1,5,2,4] result
#              3      [Get corner nodes]
#                     In this case only one
#                     [1,5,2,4,3] result
#  ------------------------------------
#  Process using head and tail node
while (current != nil && self.tail != nil)
if (current == self.tail)
#  last result node
current.next = nil
return
elsif(current.next == self.tail)
self.tail.next = nil
return
end

auxiliary = current.next
current.next = self.tail
temp = self.tail.prev
self.tail.prev = current
self.tail.next = auxiliary
if (auxiliary != nil)
auxiliary.prev = self.tail
end

current = auxiliary
#  new last node
self.tail = temp
end

end

end

def main()
#  Insert following linked list nodes
dll.insert(1)
dll.insert(2)
dll.insert(3)
dll.insert(4)
dll.insert(5)
dll.insert(6)
dll.insert(7)
dll.insert(8)
print("Before spiral conversion :\n")
dll.display()
dll.spiral()
print("\nAfter spiral conversion :\n")
dll.display()
end

main()

Output

Before spiral conversion :
Linked List Head to Tail :  1  2  3  4  5  6  7  8
Linked List Tail to Head :  8  7  6  5  4  3  2  1
After spiral conversion :
Linked List Head to Tail :  1  8  2  7  3  6  4  5
Linked List Tail to Head :  5  4  6  3  7  2  8  1

## Comment

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.