Skip to content

Instantly share code, notes, and snippets.

@NamrataSitlani
Created July 17, 2020 12:59
Show Gist options
  • Save NamrataSitlani/2c2699d0579e7afb4ed5a3da89021d54 to your computer and use it in GitHub Desktop.
Save NamrataSitlani/2c2699d0579e7afb4ed5a3da89021d54 to your computer and use it in GitHub Desktop.
Insert a node in a sorted Linked List
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def sortedInsert(self, new_node):
if self.head is None:
new_node.next = self.head
self.head = new_node
elif self.head >= new_node.data:
new_node.next = self.head
self.head = new_node
else:
current = self.head
while(current.next is not None and current.next.data <= new_node.data):
current = current.next
new_node.next= current.next
current.next = new_node
def printList(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
ll = LinkedList()
new_node= Node(2)
ll.sortedInsert(new_node)
new_node = Node(5)
ll.sortedInsert(new_node)
printLL = ll.printList()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment