I'm a beginner self-taught programmer and I am following a course on Data Structures. I've run into a snag when trying to call a get_position method after I've run append and insert methods and I don't understand why it's happening. Referencing the code below, print(ll.get_position(5).value)
prints "5" before the insert method is called and after insertion, I would expect print(ll.get_position(6).value)
would print "5" but it prints "3". Additionally I can pass any number as an argument in the get_position method and it will still print "3" or "4" even if the number is outside the bounds of the linked list. I'm assuming the while loop of the insert method is stuck? How can I reattach e5
to the linked list? Why is it getting lost?
Thank you!
class Element(object):
def __init__(self, value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self, head=None):
self.head = head
def append(self, new_element):
current = self.head
if self.head:
while current.next:
current = current.next
current.next = new_element
else:
self.head = new_element
def get_position(self, position):
counter = 1
current = self.head
while current and counter <= position:
if counter == position:
return current
current = current.next
counter += 1
def insert(self, new_element, position):
counter = 1
current = self.head
if position < 1:
return None
elif position == 1:
new_element.next = self.head
self.head = new_element
while current and counter < position:
if counter == position - 1:
new_element.next = current.next
current.next = new_element
return
current = current.next
counter += 1
# Elements in list
e1 = Element(1)
e2 = Element(2)
e3 = Element(3)
e4 = Element(4)
e5 = Element(5)
# Linked List Setup
ll = LinkedList(e1)
ll.append(e2)
ll.append(e3)
ll.append(e4)
ll.append(e5)
# Should print 5
print(ll.get_position(5).value)
ll.insert(e4, 3)
# Expected Ouput: 1,2,4,3,4
print(ll.get_position(1).value)
print(ll.get_position(2).value)
print(ll.get_position(3).value)
print(ll.get_position(4).value)
print(ll.get_position(5).value)
# Expected output: 5 (Actual Output 3)
print(ll.get_position(6).value)
# Expected output: Error. (Actual Output 4)
print(ll.get_position(7).value)
You are using the existing e4 node which is pointing to node e5. create a new element with value 4 and then pass it to insert method.
new_e4 = Element(4)
l1.insert(new_e4, 3)
After insertion of e4 you are expecting the linked list to look like
1 -> 2 -> 4 -> 3 -> 4 -> 5
But actually the linked list has become:
1 -> 2 -> 4 <=> 3 5 ( 5 is lost and 3 is pointing back to 4 and hence infinite loop)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.