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
+ def __init__ (self , data ):
3
+ self .data = data
4
+ self .next = None
5
+
6
+ class SortedLinkedList :
7
+ def __init__ (self ):
8
+ self .head = None
9
+
10
+ def insert (self , data ):
11
+ new_node = Node (data )
12
+ # Case when the list is empty or the new node needs to be at the head
13
+ if self .head is None or self .head .data >= new_node .data :
14
+ new_node .next = self .head
15
+ self .head = new_node
16
+ else :
17
+ # Find the correct position to insert the new node
18
+ current = self .head
19
+ while current .next is not None and current .next .data < new_node .data :
20
+ current = current .next
21
+ new_node .next = current .next
22
+ current .next = new_node
23
+
24
+ def display (self ):
25
+ current = self .head
26
+ while current :
27
+ print (current .data , end = " -> " )
28
+ current = current .next
29
+ print ("None" )
30
+
31
+ # Create an instance of SortedLinkedList
32
+ sll = SortedLinkedList ()
33
+ # Take input from the user
34
+ while True :
35
+ try :
36
+ user_input = input ("Enter a number (or 'q' to quit): " )
37
+ if user_input == 'q' :
38
+ break
39
+ else :
40
+ num = int (user_input )
41
+ sll .insert (num )
42
+ except ValueError :
43
+ print ("Please enter a valid number or 'q' to quit." )
44
+ # Display the sorted linked list
45
+ print ("Sorted Linked List:" )
46
+ sll .display ()
You can’t perform that action at this time.
0 commit comments