Skip to content

Instantly share code, notes, and snippets.

@naazeri
Last active March 23, 2023 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naazeri/332916d3a97b5066fd355b971f229b1d to your computer and use it in GitHub Desktop.
Save naazeri/332916d3a97b5066fd355b971f229b1d to your computer and use it in GitHub Desktop.
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self, head=None):
self.head = head
def append(self, new_node):
current = self.head
if current:
while current.next:
current = current.next
current.next = new_node
else:
self.head = new_node
def delete(self, value):
current = self.head
if current.value == value:
self.head = current.next
else:
while current:
if current.value == value:
break
prev = current
current = current.next
if current is None:
return
prev.next = current.next
current = None
def insert(self, new_element, position):
count = 1
current = self.head
if position == 1:
new_element.next = self.head
self.head = new_element
while current:
if count + 1 == position:
new_element.next = current.next
current.next = new_element
return
else:
count += 1
current = current.next
pass
def print(self):
current = self.head
while current:
print(current.value)
current = current.next
n1 = Node(2)
n2 = Node(4)
n3 = Node(6)
n4 = Node(8)
myList = LinkedList(n1)
myList.append(n3)
myList.insert(n2, 2)
myList.append(n4)
myList.delete(8)
myList.print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment