forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfrom_sequence.py
More file actions
Latest commit
57 lines (49 loc) · 1.64 KB
/
Copy pathfrom_sequence.py
File metadata and controls
57 lines (49 loc) · 1.64 KB
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
"""
Recursive Program to create a Linked List from a sequence and
print a string representation of it.
"""
classNode:
def__init__(self, data=None):
self.data=data
self.next=None
def__repr__(self):
"""Returns a visual representation of the node and all its following nodes."""
string_rep=""
temp=self
whiletemp:
string_rep+=f"<{temp.data}> ---> "
temp=temp.next
string_rep+="<END>"
returnstring_rep
defmake_linked_list(elements_list: list|tuple) ->Node:
"""
Creates a Linked List from the elements of the given sequence
(list/tuple) and returns the head of the Linked List.
>>> make_linked_list([])
Traceback (most recent call last):
...
ValueError: The Elements List is empty
>>> make_linked_list(())
Traceback (most recent call last):
...
ValueError: The Elements List is empty
>>> make_linked_list([1])
<1> ---> <END>
>>> make_linked_list((1,))
<1> ---> <END>
>>> make_linked_list([1, 3, 5, 32, 44, 12, 43])
<1> ---> <3> ---> <5> ---> <32> ---> <44> ---> <12> ---> <43> ---> <END>
>>> make_linked_list((1, 3, 5, 32, 44, 12, 43))
<1> ---> <3> ---> <5> ---> <32> ---> <44> ---> <12> ---> <43> ---> <END>
"""
# if elements_list is empty
ifnotelements_list:
raiseValueError("The Elements List is empty")
# Set first element as Head
head=Node(elements_list[0])
current=head
# Loop through elements from position 1
fordatainelements_list[1:]:
current.next=Node(data)
current=current.next
returnhead