Reputation: 105
class node(object):
def __init__(self):
self.data = None #Contains data
self.next = None #Contains the reference to the next node
self.position = 0
def get_data(self):
return self.data
def get_next(self):
return self.next_node
def set_next(self, new_next):
self.next_node = new_next
class LinkedList:
def __init__(self):
self.head = None
def add_node(self,data):
new_node = node() #Creates a new node
new_node.data = data
new_node.next = self.head #Referencing
self.head = new_node #Set the next code as the current node
def get(self,index):
current = self.head
while current:
if current.position == index:
print current.data
break
else:
current = current.next
print("None")
So I can't figure out how to make the get function work properly. It just returns 0 no matter what index I put it.
Upvotes: 1
Views: 56
Reputation: 8376
You never actually set the position
property on your node. I see no reason to store a position, though, you can just keep an index while iterating over the list.
For example:
def get(self, index):
current = self.head
while current and index >= 0:
if index == 0:
return current.data
current = current.next
index -= 1
Upvotes: 1