如何在双向链表中实现插入方法?

时间:2015-10-07 23:18:06

标签: python algorithm list class insert

我需要在我的双向链表中实现这个insert函数,并且我无法在给定索引处正确插入元素。我能够将一个元素添加到空列表对象中,但是当我尝试在最后一个节点添加一个新节点时,我收到一条错误消息:

  

' NoneType'对象没有属性' setPrev'

我理解这个错误意味着什么,并试图改变我的功能以避免此错误并获得正确的输出,但无济于事。

问题:如何修复此插入功能以允许它在所有情况下添加节点?

class DLLNode:
    def __init__(self,initdata):
        self.data = initdata
        self.next = None
        self.prev = None

    def __str__(self):
        return str(self.data)

    def getData(self):
        return self.data

    def getNext(self):
        return self.next

    def getPrev(self):
        return self.prev

    def setData(self, new_data):
        self.data = new_data

    def setNext(self, new_next):
        self.next = new_next

    def setPrev(self, new_prev):
        self.prev = new_prev

class DLL:
    """ Class representing a doubly-linked list. """

    def __init__(self):
        """ Constructs an empty doubly-linked list. """
        self.head = None
        self.size = 0

    def __str__(self):
        """ Converts the list into a string representation. """
        current = self.head
        rep = ""
        while current != None:
            rep += str(current) + " "
            current = current.getNext()

        return rep

    def isEmpty(self):
        """ Checks if the doubly-linked list is empty. """
        return self.size <= 0

    def insert(self, item, index):
        """ Inserts a node at the specified index. """
        # Construct node.
        current = self.head
        n = DLLNode(item)

        # Check index bounds.
        if index > self.size:
            return 'index out of range'

        # If the list is empty...
        if self.isEmpty():
            self.head = n
            self.head.setPrev(self.head)

        # If the index is the first node...
        if index == 0:
            n.setNext(self.head)
            self.head = n
            if self.size == 0:
                self.prev = n
        # If the index is the last node...
        elif index == self.size:
            n.next.setPrev(n)

        # If the index is any other node...
        else:
            if current == None:
                n.setPrev(self.prev)
                self.prev.setNext(n)
                self.prev = n
            else:
                n.setNext(current)
                n.getPrev().setNext(n)
                current.setPrev(n.getPrev())
                n.setPrev(n)

        self.size += 1

测试用例是以下场景:

l = DLL()
l.insert(88, 0)
l.insert(99, 1)
l.insert(77, 2)
l.insert(55, 3)
l.insert(34, 1)
l.insert(3, 0)
l.insert(15, 6)
l.insert(100, 8)
print("list after inserts", l)

输出如下:

Index out of range.
list after inserts 3 88 34 99 77 55 15 """

2 个答案:

答案 0 :(得分:1)

问题是n是你自己构建的DLLNode。默认情况下,prevnext设置为Null;因此你不能在它们上面调用任何方法。

def insert(self, item, index):
    """ Inserts a node at the specified index. """
    # Construct node.
    current = self.head
    n = DLLNode(item)

    # Check index bounds.
    if index > self.size:
        return 'index out of range'

    # If the list is empty...
    if self.isEmpty():
        self.head = n
        self.head.setPrev(self.head)
    else : #added else case to prevent overlap
        for x in range(0,index-1): #Obtain the current
            current = current.next #move to the next item
        # If the index is the first node...
        if index == 0:
            n.setNext(self.head)
            self.head = n
            if self.size == 0:
                self.prev = n
        # If the index is the last node...
        elif index == self.size:
            current.setNext(n) #set n to be the next of current
            n.setPrev(current) #set current to be the previous of n

        # If the index is any other node...
        else:
            n.setNext(current.next)
            n.setPrev(current)
            if current.next != None :
                current.next.setPrev(n)
            current.setNext(n)

    self.size += 1

最后一种情况如下:

 /------\|
C    N   X
|\------/

C current X the下一个of当前and N the n (new node). First we set the上一个{{1} }下一and N`:

of

现在我们检查 /------\| C <--N-->X |\------/ 是否真的是一个真实的节点(尽管这绝对不是必需的,因为上面已经处理了“最后的节点”)。如果X不是X,我们会将None的{​​{1}}设置为prev

X

最后,我们不再需要N指向 /------\| C <--N-->X |\-/ (否则我们无法调用C的函数),因此我们设置X X转到next

C

您是否可以提供测试数据来测试实施是否正常?

答案 1 :(得分:0)

我相信问题就在这里

elif index == self.size:
    n.next.setPrev(n)

当插入最后一个元素时,您需要遍历当前最后一个元素last。假设你做到了,你可以做到

elif index == self.size:
    last.setNext(n)
    n.setPrev(last)
    n.setNext(head) #only if this list is also circular
    self.size++