2015年3月6日星期五

Week 8:Linked node and Linked list

After attending two lectures, still, I didn't understand what a linked list really is. My way to understand a OOP concept is to generate a diagram in my head when implementing functions or initializing the object. Unfortunately, no pictures ever appeared when I saw Danny's codes for LLNode and LinkedList until I read the reading Danny posted: http://openbookproject.net/thinkcs/python/english3e/linked_lists.html



Generally, a LinkedList(formed by LLNodes) has three variables: front(represents the first node), back(refers to the last node), and size(stands for the number of the nodes in the LinkedList). 

Now while implementing methods I can understand what each line for. 
For example:

def insert_before(lnk, v1, v2):
    ''' (LinkedList, object) -> NoneType

    Insert a new node with value v1 before the first occurrence
    of a node with value v2.  Do nothing if no node has value
    v2.

    >>> lnk = LinkedList()
    >>> lnk.prepend(5)
    >>> insert_before(lnk, 4, 5)
    >>> print(lnk.front)
    4 -> 5 ->|
    >>> insert_before(lnk, 3, 5)
    >>> print(lnk.front)
    4 -> 3 -> 5 ->|
    >>> insert_before(lnk, 3, 7)
    >>> print(lnk)
    4 -> 3 -> 5 ->|
    '''
    if lnk.size > 0:
        prev_node = None   #always before cur_node
        cur_node = lnk.front
        while cur_node and not cur_node.value == v2: #if not None not v2, keep walking along the list
            prev_node = cur_node
            cur_node = cur_node.nxt
        if cur_node and cur_node.value == v2: #if cur_node is v2
            cur_node = LLNode(v1, cur_node)
            if prev_node is None: #if the cur_node is the first
                lnk.front = cur_node
            else:
                prev_node.nxt = cur_node
        lnk.size += 1#always remember to change the size of a modified link 

This week I prepared for the second term test by reviewing labs and doing couple danny's past exams. Good luck!

没有评论:

发表评论