Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update LinkedList0.py #133

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 30 additions & 29 deletions LinkedLists/LinkedList0.py
Original file line number Diff line number Diff line change
@@ -1,69 +1,70 @@
class Node(object):
class Node:
def __init__(self, data, next_node=None):
self.data = data
self.next_node = next_node

def __init__ (self, d, n = None):
self.data = d
self.next_node = n

def get_next (self):
def get_next(self):
return self.next_node

def set_next (self, n):
self.next_node = n
def set_next(self, next_node):
self.next_node = next_node

def get_data (self):
def get_data(self):
return self.data

def set_data (self, d):
self.data = d

def set_data(self, data):
self.data = data

class LinkedList (object):

def __init__(self, r = None):
self.root = r
class LinkedList:
def __init__(self, root=None):
self.root = root
self.size = 0

def get_size (self):
def get_size(self):
return self.size

def add (self, d):
new_node = Node (d, self.root)
def add(self, data):
new_node = Node(data, self.root)
self.root = new_node
self.size += 1

def remove (self, d):
def remove(self, data):
this_node = self.root
prev_node = None

while this_node:
if this_node.get_data() == d:
if this_node.get_data() == data:
if prev_node:
prev_node.set_next(this_node.get_next())
else:
self.root = this_node.get_next()
self.size -= 1
return True # data removed
return True
else:
prev_node = this_node
this_node = this_node.get_next()
return False # data not found

def find (self, d):
# Raise an exception if the data is not found
raise ValueError(f"{data} not found in the list.")

def find(self, data):
this_node = self.root
while this_node:
if this_node.get_data() == d:
return d
if this_node.get_data() == data:
return this_node
else:
this_node = this_node.get_next()
return None


myList = LinkedList()
myList.add(5)
myList.add(8)
myList.add(12)
print("size="+str(myList.get_size()))
print("size = " + str(myList.get_size()))
myList.remove(8)
print("size="+str(myList.get_size()))
print("size = " + str(myList.get_size()))
print(myList.remove(12))
print("size="+str(myList.get_size()))
print(myList.find(5))
print("size = " + str(myList.get_size()))
print(myList.find(5).get_data())