-
Notifications
You must be signed in to change notification settings - Fork 1
/
Insert_in_a_Sorted_List.py
69 lines (57 loc) · 1.59 KB
/
Insert_in_a_Sorted_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
#{
# Driver Code Starts
# Node Class
class Node:
def __init__(self, data): # data -> value stored in node
self.data = data
self.next = None
# Linked List Class
class LinkedList:
def __init__(self):
self.head = None
self.prev=self.head
# creates a new node with given value and appends it at the end of the linked list
def append(self, new_value):
new_node = Node(new_value)
if self.head is None:
self.head = new_node
self.prev = self.head
else:
self.prev.next = new_node
self.prev = self.prev.next
def printList(head):
while head:
print(head.data, end=' ')
head = head.next
print()
# } Driver Code Ends
class Solution:
def sortedInsert(self, head1,key):
curr = head1
key1=Node(key)
if head1.data >= key:
temp=curr
head1=key1
head1.next=temp
while(curr.data<key and curr):
if curr.next==None:
curr.next=key1
elif curr.next.data>=key:
temp =curr.next
curr.next=key1
key1.next=temp
curr=curr.next
return head1
#{
# Driver Code Starts.
if __name__ == '__main__':
for _ in range(int(input())):
n = int(input())
a = LinkedList()
nodes = list(map(int, input().strip().split()))
for x in nodes:
a.append(x)
key=int(input())
h=Solution().sortedInsert(a.head,key)
printList(h)
# } Driver Code Ends