Python 3 Linked List Insert Element Problem
Implement a method, insert_first which takes a linked list as a parameter and elem, and returns a new list, where elem was inserted as a first node.
def insert_first(s, elem):
'''
>>> insert_first(link(3, link(2, link(1, "empty"))),100)
[100, [3, [2, [1, 'empty']]]]
'''
Implement a method, insert_last which takes a linked list as a parameter and elem, and returns a new list, where elem was inserted as a last node.
def insert_last(s, elem):
'''
>>> lst = link(2, link(1, empty))
>>> insert_last(lst,100)
[2, [1, [100, 'empty']]]
'''
Implement insert_at which takes a linked-list, an element elem and an insertion index idx and returns the list with the element inserted at the correct location.
def insert_at(s, elem, idx):
'''
>>> lst = link(3, link(2, link(1, empty)))
>>> insert_at(lst, 4, 0)
[4, [3, [2, [1, 'empty']]]]
>>> insert_at(lst, 4, 2)
[3, [2, [4, [1, 'empty']]]]
'''
IMPORTANT Information:
empty = 'empty'
def is_link(s):
"""s is a linked list if it is empty or a (first, rest) pair."""
return s == empty or (len(s) == 2 and is_link(s[1]))
def link(first, rest):
"""Construct a linked list from its first element and the rest."""
assert is_link(rest), "rest must be a linked list."
return [first, rest]
def first(s):
"""Return the first element of a linked list s."""
assert is_link(s), "first only applies to linked lists."
assert s != empty, "empty linked list has no first element."
return s[0]
def rest(s):
"""Return the rest of the elements of a linked list s."""
assert is_link(s), "rest only applies to linked lists."
assert s != empty, "empty linked list has no rest."
return s[1]
# define length
def len_link(s):
"""Return the length of linked list s."""
length = 0
while s != empty:
s, length = rest(s), length + 1
return length
# getitem
def getitem(s, i):
"""Return the element at index i of linked list s."""
while i > 0:
s, i = rest(s), i - 1
return first(s)