Created
September 15, 2022 03:23
-
-
Save muaddib1971/25fc2070925f47449815d1ae68aee57c to your computer and use it in GitHub Desktop.
linked list example
This file contains 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
class Node: | |
def __init__(self, num: int) -> None: | |
self.num = num | |
self.next = None | |
class LinkedList: | |
def __init__(self): | |
self.len = 0 | |
self.head = None | |
def add(self, num: int) -> bool: | |
anode = Node(num) | |
if self.head is None: | |
self.head = anode | |
self.len += 1 | |
return True | |
current = self.head | |
prev = None | |
while current is not None and current.num < num: | |
prev = current | |
current = current.next | |
if current is None: | |
prev.next = anode | |
else: | |
anode.next = current | |
prev.next = anode | |
self.len += 1 | |
def print(self): | |
current = self.head | |
while current is not None: | |
print(current.num) | |
current = current.next | |
def delete(self, num): | |
current = self.head | |
prev = None | |
while current is not None and current.num <= num: | |
if current.num == num: | |
if prev is None: | |
self.head = self.head.next | |
else: | |
prev.next = current.next | |
return True | |
prev = current | |
current = current.next | |
if current is None: | |
return False | |
mylist = LinkedList() | |
mylist.add(1) | |
mylist.add(2) | |
mylist.add(4) | |
mylist.add(3) | |
mylist.delete(1) | |
mylist.print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment