This repository has been archived by the owner on Jan 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
single_linked_list.py
executable file
·79 lines (60 loc) · 1.61 KB
/
single_linked_list.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env python3
"""
Single linked list examples
"""
class ListNode:
"""
Single linked list class
"""
def __init__(self, data=0, next=None):
self.data = data
self.next = next
def print_list(start_node: ListNode):
"""
Print all nodes in the list starting at the
passed in node
"""
ptr = start_node
while True:
print(f"Data is: {ptr.data}")
print(f"Next is: {ptr.next}")
if ptr.next is None:
break
else:
ptr = ptr.next
def insert_after(after_node: ListNode, new_node: ListNode):
"""
Insert a node (new_node) into the linked list
after the 'after_node'
"""
new_node.next = after_node.next
after_node.next = new_node
def search_list(search_node: ListNode, search_key: int):
"""
Traverse the list and search for the data passed in
as the search_key
"""
while search_node and search_node.data != search_key:
search_node = search_node.next
return search_node
def main():
"""
Simple single list list demo
"""
print(f"Single Linked List testing")
# Create an initial 1 node linked list
node01 = ListNode(10, None)
# Insert some more nodes
insert_after(node01, ListNode(20))
insert_after(node01.next, ListNode(40))
print("\nPrinting all nodes.")
print_list(node01)
search_num = 40
print(f"\nSearching for {search_num}")
result = search_list(node01, search_num)
if result:
print(f"Found. Data was: {result.data}")
else:
print(f"No result found.")
if __name__ == "__main__":
main()