use python: singly linked list class 1. Re-implement the remove method so that i
ID: 3805437 • Letter: U
Question
use python: singly linked list class
1. Re-implement the remove method so that it works correctly in the case where the item is not in the list
Code
class Node:
def __init__(self,initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newdata):
self.data = newdata
def setNext(self,newnext):
self.next = newnext
class UnorderedList:
def __init__(self):
self.head = None
def isEmpty(self):
return self.head == None
def add(self,item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
def size(self):
current = self.head
count = 0
while current != None:
count = count + 1
current = current.getNext()
return count
def search(self,item):
current = self.head
found = False
while current != None and not found:
if current.getData() == item:
found = True
else:
current = current.getNext()
return found
def remove(self,item):
current = self.head
previous = None
found = False
while not found:
if current.getData() == item:
found = True
else:
previous = current
current = current.getNext()
if previous == None:
self.head = current.getNext()
else:
previous.setNext(current.getNext())
Explanation / Answer
PROGRAM CODE:
# your code goes here
class Node:
def __init__(self,initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newdata):
self.data = newdata
def setNext(self,newnext):
self.next = newnext
class UnorderedList:
def __init__(self):
self.head = None
def isEmpty(self):
return self.head == None
def add(self,item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
def size(self):
current = self.head
count = 0
while current != None:
count = count + 1
current = current.getNext()
return count
def search(self,item):
current = self.head
found = False
while current != None and not found:
if current.getData() == item:
found = True
else:
current = current.getNext()
return found
def remove(self,item):
current = self.head
previous = None
found = False
while not found:
if current.getData() == item:
found = True
if current.getNext() != None:
current.setData(current.getNext().getData())
current.setNext(current.getNext().getNext())
else:
previous.setNext(None);
else:
previous = current
current = current.getNext()
if current == None:
found = True;
#main function running here
input = UnorderedList();
input.add(2);
input.add(4);
print(input.size()) # output is 2
input.remove(2);
print(input.size()) # output is 1
input.add(6);
input.add(3);
print(input.size()) # output is 3
input.remove(2); # 2 is already removed
print(input.size()) # output is 3
OUTPUT:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.