|
| 1 | +# Copyright (C) Deepali Srivastava - All Rights Reserved |
| 2 | +# This code is part of DSA course available on CourseGalaxy.com |
| 3 | + |
| 4 | +class Node(object): |
| 5 | + |
| 6 | + def __init__(self,value): |
| 7 | + self.info = value |
| 8 | + self.link = None |
| 9 | + |
| 10 | +class SortedLinkedList(object): |
| 11 | + |
| 12 | + def __init__(self): |
| 13 | + self.start = None |
| 14 | + |
| 15 | + def insert_in_order(self, data): |
| 16 | + temp = Node(data) |
| 17 | + |
| 18 | + # List empty or node to be inserted before first node |
| 19 | + if self.start == None or data < self.start.info: |
| 20 | + temp.link = self.start |
| 21 | + self.start = temp |
| 22 | + return |
| 23 | + |
| 24 | + p = self.start |
| 25 | + while p.link is not None and p.link.info <= data: |
| 26 | + p = p.link |
| 27 | + temp.link = p.link |
| 28 | + p.link = temp |
| 29 | + |
| 30 | + |
| 31 | + def create_list(self): |
| 32 | + n = int(input("Enter the number of nodes : ")) |
| 33 | + if n == 0: |
| 34 | + return |
| 35 | + |
| 36 | + for i in range(n): |
| 37 | + data = int(input("Enter the element to be inserted : ")) |
| 38 | + self.insert_in_order(data) |
| 39 | + |
| 40 | + def search(self, x): |
| 41 | + if self.start is None: |
| 42 | + print("List is empty") |
| 43 | + return |
| 44 | + p = self.start |
| 45 | + position = 1 |
| 46 | + while p is not None and p.info <= x: |
| 47 | + if p.info == x: |
| 48 | + break |
| 49 | + position+=1 |
| 50 | + p = p.link |
| 51 | + |
| 52 | + if p is None or p.info != x: |
| 53 | + print(x," not found in list") |
| 54 | + else: |
| 55 | + print(x , " is at position " , position) |
| 56 | + |
| 57 | + def display_list(self): |
| 58 | + if self.start is None: |
| 59 | + print("List is empty") |
| 60 | + return |
| 61 | + print("List is : ") |
| 62 | + p = self.start |
| 63 | + while p is not None: |
| 64 | + print(p.info , " ", end='') |
| 65 | + p = p.link |
| 66 | + print() |
| 67 | + |
| 68 | +######################################################################## |
| 69 | + |
| 70 | +list = SortedLinkedList() |
| 71 | +list.create_list() |
| 72 | + |
| 73 | +while True: |
| 74 | + print("1.Display list") |
| 75 | + print("2.Insert") |
| 76 | + print("3.Search for an element") |
| 77 | + print("4.Quit") |
| 78 | + |
| 79 | + option = int(input("Enter your choice : " )) |
| 80 | + |
| 81 | + if option == 1: |
| 82 | + list.display_list() |
| 83 | + elif option == 2: |
| 84 | + data = int(input("Enter the element to be inserted : ")) |
| 85 | + list.insert_in_order(data) |
| 86 | + elif option == 3: |
| 87 | + data = int(input("Enter the element to be searched : ")) |
| 88 | + list.search(data) |
| 89 | + elif option == 4: |
| 90 | + break |
| 91 | + else: |
| 92 | + print("Wrong option") |
| 93 | + print() |
| 94 | + |
| 95 | + |
| 96 | + |
| 97 | + |
0 commit comments