-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertNodeAtTail.py
More file actions
49 lines (33 loc) · 998 Bytes
/
Copy pathinsertNodeAtTail.py
File metadata and controls
49 lines (33 loc) · 998 Bytes
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
from typing import Type, Optional
import sys
class SinglyLinkedListNode:
def __init__(self, node_data: int):
self.data = node_data
self.n: Optional[SinglyLinkedListNode] = None
class SinglyLinkedList:
def __init__(self):
self.head: Optional[SinglyLinkedListNode] = None
def print_singly_linked_list(node, sep, fptr):
while node:
fptr.write(str(node.data))
node = node.n
if node:
fptr.write(sep)
def insertNodeAtTail(
head: Optional[SinglyLinkedListNode], data: int
) -> SinglyLinkedListNode:
node = SinglyLinkedListNode(data)
if head is None:
return node
else:
curr = head
while curr.n is not None:
curr = curr.n
curr.n = node
return head
arr = [141, 302, 164, 530, 474]
llist = SinglyLinkedList()
for item in arr:
llHead = insertNodeAtTail(llist.head, item)
llist.head = llHead
print_singly_linked_list(llist.head, "\n", sys.stdout)