File tree 1 file changed +46
-0
lines changed
data_structures/linked_list
1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Node :
2
+ """class to represent a node in a linked list."""
3
+ def __init__ (self , data ):
4
+ self .data = data # store the value of the node
5
+ self .next = None # pointer to the next node
6
+
7
+
8
+ def array_to_linked_list (arr ):
9
+ """Convert an array to a linked list and return the head of the linked list."""
10
+ if arr is None : # checking if the input array is empty
11
+ return None # if empty it will return nothing
12
+
13
+ head = Node (arr [0 ]) # create head node
14
+ n = head # pointer to the head node
15
+
16
+ # loop through the array starting from the second element coz 1st element is head
17
+ for value in arr [1 :]:
18
+ n .next = Node (value ) # creating a new node
19
+ n = n .next
20
+
21
+ return head
22
+
23
+
24
+ def print_linked_list (head ):
25
+ """printing the linked list."""
26
+ n = head
27
+ while n is not None :
28
+ print (n .data , end = " -> " if n .next else "" )
29
+ n = n .next
30
+ print (" -> Null" ) # for a new line at end which will also add -> null at end
31
+
32
+
33
+ # main function to take user input
34
+ def main ():
35
+ user_input = input ("Enter a list of integers separated by spaces: " )
36
+
37
+ arr = list (map (int , user_input .split ())) # convert input string to a list of integers
38
+
39
+ linked_list_head = array_to_linked_list (arr )
40
+
41
+ print ("Linked List: " , end = "" )
42
+ print_linked_list (linked_list_head )
43
+
44
+
45
+ if __name__ == "__main__" :
46
+ main ()
You can’t perform that action at this time.
0 commit comments