Skip to content

Instantly share code, notes, and snippets.

@rtacconi
Created August 8, 2020 14:13
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 rtacconi/ee7920d1c6c0020b029a2bbbb9ba736d to your computer and use it in GitHub Desktop.
Save rtacconi/ee7920d1c6c0020b029a2bbbb9ba736d to your computer and use it in GitHub Desktop.
Implementation of Singly linked list
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def __str__(self):
return str(self.data)
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def clear(self):
self.tail = None
self.head = None
def show(self):
for word in words.iter():
print(word)
def append(self, data):
# Encapsulate the data in a Node
node = Node(data)
self.size += 1
if self.head:
self.head.next = node
self.head = node
else:
self.tail = node
self.head = node
def iter(self):
current = self.tail
while current:
val = current.data
current = current.next
yield val
def find(self, data):
current = self.tail
node = None
while current:
if current.data == data:
node = current
current = current.next
return node
def search(self, data):
'''Same as search but using iterators'''
for d in self.iter():
if data == d:
return True
return False
def delete(self, data):
current = self.tail
prev = self.tail
while current:
if current.data == data:
if current == self.tail:
self.tail = current.next
else:
prev.next = current.next
self.size -= 1
return
prev = current
current = current.next
words = SinglyLinkedList()
words.append('eggs')
words.append('ham')
words.append('spam')
words.find('eggs').next.data
words.delete('eggs')
words.search('eggs')
words.show()
words.clear()
words.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment