Learn practical skills, build real-world projects, and advance your career
Updated 3 years ago
Linked List
Table Of Contents
Use Case 1: Phone Directory
Phone directory: Problem statement
Let’s create a phone directory using Linked list.
Details in a node are name and phone number.
We need to insert the nodes in the linked list in a sorted order by the name.
# Create a Node to store the contact
class Contact:
def __init__(self, name, number, nextContact=None):
self.name = name
self.number = number
self.nextContact = nextContact
#print("Constructor called")
#print("Name, Number, NextPointer: ",self.name," | ",self.number," | ",self.nextContact)
# Create a class PhoneDirectory: add_contact(), display_phone_directory()
class PhoneDirectory:
def __init__(self):
self.root = None
print("Phone Directory constructor called. Root= ",self.root)
def add_contact(self, contact):
if self.root is None:
self.root = contact
print("self.root.name: ",self.root.name)
print("self.root.number: ",self.root.number)
print("self.root.nextContact: ",self.root.nextContact)
# print(contact)
elif self.root.name > contact.name:
contact.nextContact = self.root
self.root = contact
else:
current = self.root
while current.name < contact.name and current.nextContact is not None:
current = current.nextContact
contact.nextContact = current.nextContact
current.nextContact = contact
def display_phone_directory(self):
phone_directory = PhoneDirectory()
phone_directory.add_contact(Contact("abc",121))
phone_directory.add_contact(Contact("adc",122))
Phone Directory constructor called. Root= None
self.root.name: abc
self.root.number: 121
self.root.nextContact: None
l = [ 10,20,30,40 ]
print(id(l))
for i in l:
print(id(i))
print("==========================")
l.insert(2,50)
print(l)
print(id(l))
for i in l:
print(id(i))
1766448563904
140722308786240
140722308786560
140722308786880
140722308787200
==========================
[10, 20, 50, 30, 40]
1766448563904
140722308786240
140722308786560
140722308787520
140722308786880
140722308787200