I'm implementing a linked list containing only values, and am attempting to utilize recursion to traverse the list to insert a specific value at a specific position in the list. I've solved how to do this using a while loop, however, I'm having trouble translating this into a recursive function.
The insert method includes both the value and the index as parameters, and if the position is 0 the function will set the head node to the new value. Else, I create a new_node variable set to the head of the node and, while the position is greater than 1, new_nodeis set to the next node and index is decremented by 1. I can insert using this method but I've been unable to implement this using recursion.
My iterative solution
class Node:
def __init__(self, data, node=None):
self._data = data
self._next = node
def get_next(self):
return self._next
def get_data(self):
return self._data
def set_next_node(self, val):
self._next = val
class LinkedList:
def __init__(self):
self._head = None
def get_head(self):
return self._head
def set_head(self, value):
self._head = value
def insert(self, value, index):
if index == 0:
self._head = Node(value, self._head)
return
new_node = self._head
while index > 1:
new_node = new_node.get_next()
index -= 1
new_node._next = Node(value, new_node.get_next())