Skip to content

Instantly share code, notes, and snippets.

@riceball1
Created July 24, 2021 23:44
Show Gist options
  • Save riceball1/0fbab21edeec01646564cf37e7aa51ef to your computer and use it in GitHub Desktop.
Save riceball1/0fbab21edeec01646564cf37e7aa51ef to your computer and use it in GitHub Desktop.
Linked List Example
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
if position < 1:
return None
while current and counter <= position:
if counter == position:
return current
current = current.next
counter += 1
return None
def insert(self, new_element, position):
counter = 1
current = self.head
if position > 1:
while current and counter < position:
if counter == position - 1:
new_element.next = current.next
current.next = new_element
current = current.next
counter += 1
elif position == 1:
new_element.next = self.head
self.head = new_element
def delete(self, value):
current = self.head
previous = None
while current.value != value and current.next:
previous = current
current = current.next
if current.value == value:
if previous:
previous.next = current.next
else:
self.head = current.next
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment