简体   繁体   English

Python 3插入到双向链接列表中

[英]Python 3 Inserting Into a Doubly Linked List

Just to start, this is homework, so I'm merely looking for a hint here. 刚开始,这是家庭作业,所以我只是在这里寻找提示。 I'm pretty new to Python and programming in general. 一般而言,我对Python和编程还很陌生。 I'm supposed to implement a cursor-based list that is doubly linked. 我应该实现一个双向链接的基于游标的列表。 I'm having some trouble with inserting onto the list. 我在插入列表时遇到了一些麻烦。 My instructor provided a simple Node class aa Node2Way class. 我的讲师提供了一个简单的Node类和Node2Way类。 He also provided the init method: 他还提供了init方法:

from node import Node

class Node2Way(Node):
    def __init__(self,initdata):
        Node.__init__(self,initdata)
        self.previous = None

    def getPrevious(self):
        return self.previous

    def setPrevious(self,newprevious):
        self.previous = newprevious

Here is what I have so far (just the pertinent methods): 这是到目前为止我所拥有的(只是相关方法):

from node2way import Node2Way

class CursorBasedList(object):
    """ Linked implementation of a positional list."""

    def __init__(self):
        """ Creates an empty cursor-based list."""
        self._header = Node2Way(None)
        self._trailer = Node2Way(None)
        self._trailer.setPrevious(self._header)
        self._header.setNext(self._trailer)
        self._current = None
        self._size = 0

def insertAfter(self, item):
        """Inserts item after the current item, or
        as the only item if the list is empty.  The new item is the
        current item."""
        temp = Node2Way(item)
        if self.isEmpty():
            self._header.setNext(temp)
            self._trailer.setPrevious(temp)
        else:
            temp.setNext(self._current.getNext())
            self._current.setNext(temp)
            temp.setPrevious(self._current)
        self._current = temp
        self._size+=1

When I test the insertAfter method out, it works for adding the first item, but when I try to add the second item, it says that self._current is None type and can't use the getNext method. 当我测试出insertAfter方法时,它可以用于添加第一项,但是当我尝试添加第二项时,它说self._current是None类型,不能使用getNext方法。 I don't know if there is another way to get temp to reference the node after the current one. 我不知道是否有另一种方法可以使temp在当前节点之后引用该节点。 I'm not sure what I'm doing wrong, or even if anything I'm doing is right. 我不确定自己在做什么错,或者即使我做错了什么。 I think once I get the insertAfter method right, I'll be fine with the insertBefore method. 我认为,一旦我正确使用insertAfter方法,就可以使用insertBefore方法。

Any hints would be appreciated. 任何提示将不胜感激。 Thank you in advance! 先感谢您! :) :)

In the case of 如果是

    if self.isEmpty():
        self._header.setNext(temp)
        self._trailer.setPrevious(temp)

You never set the previous and next nodes of temp . 您永远不会设置temp的上一个和下一个节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM