Saturday, 7 March 2015

Week 8: Linked Lists

This week during lectures we learned about a type of degenerate Tree called a LinkedList. In short,
each linked list has a front and back marker as well as a size which represents the number of nodes the list contains. Below is the code for both class LLNode and class LinkedList:

class LLNode:
    '''Node to be used in linked list
    nxt: LLNode -- next node
                   None iff we're at end of list
    value: object --- data for current node
    '''

    def __init__(self, value, nxt=None):
        ''' (LLNode, object, LLNode) -> NoneType

        Create LLNode (self) with data value and successor nxt.
        '''

        self.value, self.nxt = value, nxt

    def __str__(self):
        ''' (LLNode) -> str

        Return a user-friendly representation of this LLNode.

        >>> n = LLNode(5, LLNode(7))
        >>> print(n)
        5 -> 7 ->|
        '''

        if self.nxt is None:
            return '{} ->|'.format(str(self.value))
        else:
            return '{} -> {}'.format(str(self.value), str(self.nxt))

class LinkedList:
    '''Collection of LLNodes organized into a linked list.
    front: LLNode -- front of list
    back:  LLNode -- back of list'''

    def __init__(self):
        ''' (LinkedList) -> NoneType

        Create an empty linked list.
        '''

        self.front, self.back = None, None
        self.size = 0

For this week's lab handout, we were tasked with implementing several different functions that mutated Linked Lists, either updating values at particular nodes, inserting a node before another node, or deleting nodes all together. In traversing Linked Lists, it is important to understand that you cannot update backwards only forwards. So, if I 'overshoot' and find my node, I can't delete it or insert something behind it since I would have needed to do that in the previous node to the one desired. In these cases, two reference markers can be used, one for the current node and one for the node just prior. Below are some examples from the handout to illustrate the concepts better:

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 v2 not in lnk:
        return # We use the special method __contains__
   
    current = lnk.front
   
    if current.value == v2:
        lnk.prepend(v1) # Only for if v2 is the very first element in the LL
                                  # then there is no 'previous' node to reference

    else:
        while current.value != v2:
            pre = current
            current = current.nxt
        pre.nxt = LLNode(v1)
        pre.nxt.nxt = current

Here we have 3 cases. First, if v2 is not in lnk, then we just return without updating the list. This is easily checked using 'v2 in lnk' since we already have a special method __contains__ for class LinkedList. Secondly, we must separately check is the first node's value in lnk equals v2. In this case, we will prepend v1 (Note that in this case, the start of the list is already 'too late' so we need to use prepend). Thirdly, if the above two conditions fail, then v2 is somewhere in the middle of lnk. Here we initiate a while loop for current.value != v2 which sets our previous node to the current and our current node to the next node. That way, when the while loop is broken and current.value == v2, we assign LLNode(v1) to pre.nxt and then we assign the current to pre.nxt.nxt essentially reattaching the rest of the linked list to what we just inserted.

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

    Insert a new 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 ->|
    '''
    cur = lnk.front
   
    if value not in lnk:
        return # Ensures we won't have problems in the following while loop
   
    while cur.value != value:
        cur = cur.nxt
    cur.nxt = cur.nxt.nxt # We 'skip' over the node we want deleted

Similar to the function above, we have to check that if value not in lnk, we just return without modifying lnk. However, in this case we only have two cases not three since we are deleting AFTER a given node and not inserting BEFORE so we do not have a special case for the first node. In this while loop, once we have found that cur.value == value, we assign cur.nxt.nxt to cur.nxt. What this does is skip over cur.nxt and instead attaches this to cur.nxt.nxt which is the node just after the node we want removed.

    def __add__(self, other):
        ''' (LinkedList, LinkedList) -> LinkedList

        Concatenate LinkedList (self) to LinkedList (other) and
        return a new list, leaving self and other unchanged.

        >>> lnk1 = LinkedList()
        >>> lnk1.prepend(5)
        >>> lnk2 = LinkedList()
        >>> lnk2.prepend(7)
        >>> lnk3 = lnk1.__add__(lnk2)
        >>> print(lnk3.front)
        5 -> 7 ->|
        >>> print(lnk1.front)
        5 ->|
        >>> print(lnk2.front)
        7 ->|
        '''
       
        lst = LinkedList()
       
        current_node = self.front
        while current_node != None:
            lst.append(current_node.value)
            current_node = current_node.nxt
       
        current_node = other.front
        while current_node != None:
            lst.append(current_node.value)
            current_node = current_node.nxt
       
        return lst

Here, we have a more interesting case of concatenating two linked lists without modifying either one in the process. The code above traverses each list, appending each of its values to our new linked list until the current_node == None in which case our two sub-lists have been fully exhausted. I am curious to go to office hours and see if there is a 'cleaner' way of doing this function without having to traverse both lists independently. However, my previous attempts at concatenating the two lists using self.front, self.back, etc all resulted in at least one of the two sub-lists being modified which goes against the docstring.

Overall, linked lists have proved to be quite an ingenious and useful tool in the arsenal of computer scientists and I hope to study them more in preparation of Wednesday's second midterm.

No comments:

Post a Comment