Last active
May 13, 2018 23:16
-
-
Save scriptpapi/88ed39b066e443ea828790d13954c5cb to your computer and use it in GitHub Desktop.
Basic implementation of singly linked list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Basic implementation of singly linked list | |
class Node: | |
def __init__(self, data): | |
self.data = data | |
self.next = None | |
def getData(self): | |
return self.data | |
def setData(self, newData): | |
self.data = newData | |
def getNext(self): | |
return self.next | |
def setNext(self, newData): | |
self.next = newData | |
class LinkedList: | |
def __init__(self): | |
self.head = None | |
self.size = 0 | |
def isEmpty(self): | |
return self.head is None | |
def size(self): | |
curr = self.head | |
size = 0 | |
while curr: | |
size += 1 | |
curr = curr.getNext | |
return size | |
def find(self, data): | |
curr = self.head | |
found = False | |
while curr is not None and not found: | |
if curr.getData() == data: | |
found = True | |
else: | |
curr = curr.getNext() | |
if curr is None: | |
return False | |
return curr | |
def append(self, data): | |
newNode = Node(data) | |
if self.head == Node: | |
self.head = newNode | |
else: | |
newNode.setNext(self.head) | |
self.head = newNode | |
self.size += 1 | |
def remove(self, data): | |
curr = self.head | |
prev = None | |
found = False | |
while curr and found is False: | |
if curr.getData() == data: | |
found = True: | |
else: | |
prev = curr | |
curr = curr.getNext() | |
if curr is None: | |
return False | |
if prev is None: | |
self.head = curr.getNext() | |
else: | |
prev.setNext(curr.getNext()) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment