Linked Lists: Conceptual Solutions
BOX AND POINTER DIAGRAMS
Draw the box and pointer diagrams for the following linked lists.
Link(1, Link(2, Link(3, Link(4))))
Link(6, Link(Link(7, Link(8)), Link(9, Link(10))))
Link(Link(Link(4, Link(8)), Link(12, Link(Link(16), Link(20)))), Link(24))
code writing
Write out a function that will sum up all of the values in a linked list (the linked list may be nested). Assume there is at least one value in the list.
def sum_vals(lnk):
>>> lnk = Link(1, Link(2, Link(3, Link(4))))
>>> sum_vals(lnk)
10
if lst.rest is Link.empty:
return lst.first
return lst.first + sum_vals(lst.rest)
Write out a function that will return true if y is a value in linked list lnk.
def search(lnk, y):
>>> lnk = Link(1, Link(2, Link(3, Link(4))))
>>> search(lnk, 4)
True
>>> search(lnk, 7)
False
if lnk is Link.empty:
return False
return y == lnk.first or search(lnk.rest, y)
Write out a function that will take in a linked list and remove any links with odd first values from it (by creating a new linked list, not mutating lnk).
def remove_odd_nondestructive(lnk):
>>> lnk = Link(1, Link(2, Link(3, Link(4, Link(5)))))
>>> remove_odd_nondestructive(lnk)
Link(2, Link(4))
>>> lnk
Link(1, Link(2, Link(3, Link(4, Link(5)))))
if lnk is Link.empty:
return lnk
else if lnk.first % 2 != 0:
return remove_odd_nondestructive(lnk.rest)
return Link(lnk.first,remove_odd_nondestructive(lnk.rest))