Method of getting element instance in python linked list class

  • 2021-09-11 20:35:16
  • OfStack

1. append method

After adding elements to the linked list. In a linked list, each element cannot be located by index, but only in the list. The. next method of a linked list element needs to be called continuously to get the next element, and finally the last element. The. next attribute of the last 1 element will point to the newly added element.


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

2. get_position method

Gets the position of the element in the linked list corresponding to the passed-in parameter.

You need to iterate through the linked list by calling the. next property in a loop. The difference is that we need to define a variable counter to record the order of linked list elements we traverse. We also need to return None when the passed-in parameter cannot get the linked list element.


def get_position(self, position):
counter = 1
current = self.head
if position < 1:
return None
While current and counter <= position:
if counter == position:
return current
current = current.next
counter += 1
return None

Related articles: