# Implementation of an Unordered List ADT as a linked list. The list # is access
ID: 3603438 • Letter: #
Question
# Implementation of an Unordered List ADT as a linked list. The list
# is accessed through a reference to the first element, head.
# Adopted from Section 3.9 of the textbook.
from Node import Node
class UnorderedList:
'''
List is empty upon creation and the head reference is None
'''
def __init__(self):
self.head = None
'''
Returns True if list is empty, False otherwise
'''
def is_empty(self):
return self.head == None
'''
Add an element to head of the list
'''
def add(self, item):
# Create a node using item as its data
temp = Node(item)
# make the next reference of the new node refer to the head
# of the list
temp.set_next(self.head)
# modify the list head so that it references the new node
self.head = temp
'''
Returns the size of the list
'''
def size(self):
# start at the head of the list
current = self.head
count = 0
# Traverse the list one element at a time. We know
# we reached the end when the next reference is None
while current != None:
count = count + 1
current = current.get_next()
return count
Explanation / Answer
class UnorderedList:
def __init__(self):
self.head = None
def is_empty(self):
return self.head == None
def add(self, item):
# Create a node using item as its data
temp = Node(item)
# make the next reference of the new node refer to the head # of the list
temp.set_next(self.head)
# modify the list head so that it references the new node
self.head = temp
def replace_element(self, i,newValue):
currentNode=self.head
index=0
#iterate until required node reached
while index!=i and currentNode:
currentNode=currentNode.get_next();
index+=1
#if index reached
if index==i:
currentNode.set_data(newValue)
def print_list(self):
result = "["
node = self.head
if node != None:
result += str(node.data)
node = node.next
while node:
result += ", " + str(node.data
)
node = node.next
result += "]"
print (result)
return result
class Node:
def __init__(self, init_data):
self.data = init_data
self.next = None
def get_data(self):
return self.data
def get_next(self):
return self.next
def set_data(self, new_data):
self.data = new_data
def set_next(self, new_next):
self.next = new_next
def main():
# create a list and add some elements to it
aList = UnorderedList()
print("Adding 3, 5, 8, and 11 to the list.")
aList.add(3)
aList.add(5)
aList.add(8)
# 11 is the head of the list
aList.add(11)
aList.print_list()
print("Replacing element at index 2 with 1 and elememt at 0 with 10:")
aList.replace_element(2,1)
aList.replace_element(0,10)
aList.print_list()
main()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.