Created
July 22, 2023 10:33
-
-
Save ihesvm/a83ed35544d21fee527be0a87705939a to your computer and use it in GitHub Desktop.
linked list in python example code
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, data): | |
self.data = data | |
self.next = None | |
class LinkedList(object): | |
def __init__(self): | |
self.head = None | |
def print_list(self): | |
temp = self.head | |
while temp: | |
print(temp.data) | |
temp = temp.next | |
def push(self, new_data): | |
new_node = Node(new_data) | |
new_node.next = self.head | |
self.head = new_node | |
@staticmethod | |
def insert_after(prev_node, new_data): | |
if prev_node is None: | |
print("The Given Previous Node Must in LinkedList...") | |
return | |
new_node = Node(new_data) | |
new_node.next = prev_node.next | |
prev_node.next = new_node | |
def append(self, new_data): | |
# 1. Create a new node | |
# 2. Put in the data | |
# 3. Set next as None | |
new_node = Node(new_data) | |
# 4. If the Linked List is empty, then make the | |
# new node as head | |
if self.head is None: | |
self.head = new_node | |
return | |
# 5. Else traverse till the last node | |
last = self.head | |
while last.next: | |
last = last.next | |
# 6. Change the next of last node | |
last.next = new_node |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment