class Node:
#creates node
def __init__(self, value):
self.value = value
self.next = None
class LinkedList :
def __init__(self, value):
new_node = Node(value) #creates node
self.head = new_node #
self.tail = new_node
self.length = 1 #optional, I just put it for my understanding
def print_list(self) :
temp = self.head #see the first node
while temp is not None :
print(temp.value)
temp = temp.next
def append(self, value):
new_node = Node(value)
if self.head is None :
self.head = new_node
self.tail = new_node
else :
self.tail.next = new_node
self.tail = new_node
self.length += 1
def get(self, index):
if index < 0 or index>= self.length : #when list number is out of range
return None
temp = self.head
for _ in range(index) :
temp = temp.next
return temp.value
def set_value(self, index, value ): #sets the value by getting index number and the value
temp = self.get(index)
if temp is not None : # passes the list range test. make sure it is in range
temp.value = value #THE ERROR occurs here.
return True
return False
my_LL = LinkedList(11)
my_LL.append(3)
my_LL.append(23)
my_LL.append(7)
my_LL.set_value(1,4)
print_list()
I'm doing linked list using python now.
The set value takes in the index number of the linked list and a desired value that changes the value of the index number to the desired value. for example: set_value(1, 4) would change 11->3->23->7 to 11->4->23->7 .
I tried to run the program, but got "int object has no attribute 'value' " error.
I can't figure out why the error occured and how to fix it.
You are attempting to access the value attribute of the get result, which is an integer rather than a Node object, using the set value method.
You should change the 'get' method to this:
def get(self, index):
if index < 0 or index >= self.length: #when list number is out of range
return None
temp = self.head
for _ in range(index) :
temp = temp.next
return temp
Change the 'set_value' method to this:
def set_value(self, index, value ): #sets the value by getting index number and the value
temp = self.get(index)
if temp is not None : # passes the list range test. make sure it is in range
temp.value = value
return True
return False
And you should also add my_LL. before print_list() like this:
my_LL.print_list()
Now the output should look like this:
11
4
23
7