Deleting odd numbers from a linked list in python:
In this program, we will see how to remove odd numbers from a linked list in Python.
This is a very interesting program where we will learn how to remove odd numbers from a linked list. This contains a very easy to understand method of making a linked list.
So when you know how to use the linked list we will learn how to remove odd numbers from it. (Note that the program done here is done without using recursion for further simplicity).
For removing odd number we first find out the position of the “head“. The head is the starting node in a linked list.
Source Code:
class Node:
def __init__(self,data=None,next=None):
self.data=data
self.next=next
class SingleLinkedList:
def __init__(self):
self.head=None
def print_list(self):
if self.head is None:
print("Linked list is empty ")
return
itr=self.head
elements=''
while itr:
elements+=str(itr.data)+'-->'
itr=itr.next
def insert_values(self,data_list):
self.head=None
for x in data_list:
self.insert_at_the_end(x)
def remove_odds(self):
# special case: head node
# remove odd head elements by simply setting head to the next element after
while (self.head is not None) and (self.head.data % 2 == 1):
self.head = self.head.next
# regular case: the rest of the nodes
itr = self.head
while (itr is not None) and (itr.next is not None):
# if the next node's data is odd, then
if itr.next.data % 2 == 1:
# skip that node by pointing this node's .next to the next node's .next
itr.next = itr.next.next
# otherwise, move forwards in the list
else:
itr = itr.next
if __name__=='__main__':
sll=SingleLinkedList()
def __init__(self,data=None,next=None):
self.data=data
self.next=next
class SingleLinkedList:
def __init__(self):
self.head=None
def print_list(self):
if self.head is None:
print("Linked list is empty ")
return
itr=self.head
elements=''
while itr:
elements+=str(itr.data)+'-->'
itr=itr.next
def insert_values(self,data_list):
self.head=None
for x in data_list:
self.insert_at_the_end(x)
def remove_odds(self):
# special case: head node
# remove odd head elements by simply setting head to the next element after
while (self.head is not None) and (self.head.data % 2 == 1):
self.head = self.head.next
# regular case: the rest of the nodes
itr = self.head
while (itr is not None) and (itr.next is not None):
# if the next node's data is odd, then
if itr.next.data % 2 == 1:
# skip that node by pointing this node's .next to the next node's .next
itr.next = itr.next.next
# otherwise, move forwards in the list
else:
itr = itr.next
if __name__=='__main__':
sll=SingleLinkedList()
sll.insert_values([2,1,0,3,14,13])
sll.print_list()
print(sll.get_length())
sll.remove_odds()
sll.print_list()
print(sll.get_length())
print(sll.get_length())
sll.remove_odds()
sll.print_list()
print(sll.get_length())
_______________________________________________________________
Please Like, Comment and Share for more!😉
Comments
Post a Comment