# This program exercises arrays and linked lists of nodes. # Replace any \"<your
ID: 3782284 • Letter: #
Question
# This program exercises arrays and linked lists of nodes.
# Replace any "<your code>" comments with your own code statement(s)
# to accomplish the specified task.
# Do not change any other code.
# The following files must be in the same folder:
# arrays.py
# node.py
from arrays import Array
from node import Node
# Here is the array:
theArray = Array(10)
for i in range(len(theArray)):
theArray[i] = i + 1
# Print the array:
print("The array structure:")
print(theArray)
head = Node(theArray[0], None)
tail = head
# Part 1:
# Copy the array items to a linked structure:
# The linked structure must consist of Node class items.
# You must use some form of a loop to create the linked structure.
#<your code>
print() # blank line
# Part 2:
print("The linked structure:")
# Print the linked structure with each item on a separate line.
# You must use some form of a loop to print the linked structure.
#<your code>
Explanation / Answer
---------------part 1----------------------------
class node:
def __init__(self):
self.data = None # contains the data
self.next = None # contains the reference to the next node
class linked_list:
def __init__(self):
self.cur_node = None
def add_node(self, data):
new_node = node() # create a new node
new_node.data = data
new_node.next = self.cur_node # link the new node to the 'previous' node.
self.cur_node = new_node # set the current node to the new one.
ll = linked_list()
theArray=Array(10)
for i in range(len(theArray)):
theArray[i] = i + 1
for value in theArray:
ll.add_node(value)
-------------------part 2---------------------
class node:
def __init__(self):
self.data = None # contains the data
self.next = None # contains the reference to the next node
class linked_list:
def __init__(self):
self.cur_node = None
def add_node(self, data):
new_node = node() # create a new node
new_node.data = data
new_node.next = self.cur_node # link the new node to the 'previous' node.
self.cur_node = new_node # set the current node to the new one.
def list_print(self):
node = self.cur_node # cant point to ll!
while node:
print node.data
node = node.next
ll.list_print()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.