double_linked_list in Python

连晟
2023-12-01

class Frob(object):
    def __init__(self, name):
        self.name = name
        self.before = None
        self.after = None
    def setBefore(self, before):
        # example: a.setBefore(b) sets b before a
        self.before = before
    def setAfter(self, after):
        # example: a.setAfter(b) sets b after a
        self.after = after
    def getBefore(self):
        return self.before
    def getAfter(self):
        return self.after
    def myName(self):
        return self.name
def insert(atMe, newFrob):
    """
    atMe: a Frob that is part of a doubly linked list
    newFrob:  a Frob with no links 
    This procedure appropriately inserts newFrob into the linked list that atMe is a part of.    
    """
    atMe_temp = atMe
    if newFrob.name < atMe.name:
        while True:
            new = atMe.before
            if new == None:
                break
            if new.name < newFrob.name:
                break
            atMe = atMe.before
        if new  == None:
            
            newFrob.after = atMe
            atMe.before = newFrob
        else:
            temp = new.after
            new.after = newFrob
            newFrob.before = new
            newFrob.after = temp
            temp.before = newFrob
    else:
        while True:
            new = atMe.after
            if new == None:
                break
            if new.name > newFrob.name:
                break
            atMe = atMe.after
        if new  == None:
            atMe.after = newFrob
            newFrob.before = atMe
        else:
            temp = new.before
            temp.after = newFrob
            newFrob.before = temp
            new.before = newFrob
            newFrob.after = new
            
            
eric = Frob('eric')
andrew = Frob('andrew')
ruth = Frob('ruth')
fred = Frob('fred')
martha = Frob('martha')

insert(eric, andrew)
insert(eric, ruth)
insert(eric, fred)
insert(ruth, martha)
print andrew.after.name
print eric.before.name,eric.after.name
print fred.before.name,fred.after.name
print martha.before.name,martha.after.name
print ruth.before.name
def findFront(start):
    """
    start: a Frob that is part of a doubly linked list
    returns: the Frob at the beginning of the linked list 
    """
    # Your Code Here
    if start.before == None:
        return start
    else:
        return findFront(start.before)
print findFront(martha).name
print findFront(fred).name

 类似资料:

相关阅读

相关文章

相关问答