Created
July 17, 2020 12:59
-
-
Save NamrataSitlani/2c2699d0579e7afb4ed5a3da89021d54 to your computer and use it in GitHub Desktop.
Insert a node in a sorted Linked List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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