2015年3月13日星期五

Week 9: modify BST instance


Due to the test, we only had one class this week. In the lecture, we explored BST methods which may modify the BST instance they are called on. Furthermore, mutations and iterations are not only related to BST, but to LinkList as well.

There is a general format for iterations in a LinkedList which I copied from the slide:

cur_node = self.front
while : # do something here... 
cur_node = cur_node.nxt #walk along 



After all, the test was easier than i thought and cheating sheet was really helpful for the last question. I only changed couple lines of __delete__ method.

def delete_after(lnk, value):
    ''' (LinkedList, object) -> NoneType

    Delete node with value after the first occurrence of a
    node containing value, if possible.

    >>> lnk = LinkedList()
    >>> lnk.append(3)
    >>> lnk.append(5)
    >>> lnk.append(7)
    >>> lnk.append(9)
    >>> delete_after(lnk, 3)
    >>> print(lnk)
    3 -> 7 -> 9 ->|
    >>> delete_after(lnk, 7)
    >>> print(lnk)
    3 -> 7 ->|
    >>> delete_after(lnk, 15)
    >>> print(lnk)
    3 -> 7 ->|
    '''
    if lnk.front:
        cur_node = lnk.front
        # walk along the list
        while cur_node and not cur_node.value == value:
            cur_node = cur_node.nxt  #walk along the list
        if cur_node and cur_node.nxt:
            if lnk.back is cur_node.nxt:#if the node needed to be deleted is back
                lnk.back = cur_node#just change the value of back to cur_node
            cur_node.nxt = cur_node.nxt.nxt#if not the last node, delete cur_node.nxt 
            lnk.size -= 1#always remember to change the size of a modified link

However, I forgot to draw a diagram for the last question....sadly:(

没有评论:

发表评论