制作我自己的单链接列表,无法制作insert_after函数

时间:2019-04-07 17:06:13

标签: python function singly-linked-list

我正在用python创建自己的单链接列表。我了解到,当我必须在“ p”节点之后插入时,首先,要使新节点指向p的下一个,然后使新节点指向p的下一个。

但是当我运行下面的代码时,出现了错误

class SList:
    class _Node:
        def __init__(self, element, next = None):
            self._element = element
            self._next = next

        def element(self):
            return self._element

        def next(self):
            return self._next

        def set_element(self, element):
            self._element = element

        def set_next(self, next):
            self._next = next

    def __init__(self, head = None):
        self._head = head
.
.
.
.
def insert_after(self, element, p): 
        # element is new node, and p is the node already in SLL.
        new_node = self._Node(element, p.next())
        p.next() = new_node

输出变成这样...

File "<ipython-input-100-f46148f593d4>", line 74
    element.next() = new_node
    ^
SyntaxError: can't assign to function call

所以我不能继续,因为当我输入这样的值时...

temp = SList()
temp.insert_first("A")
temp.insert_first("B")
temp.insert_first("C")
temp.insert_first("E")
temp.insert_first("F")

temp.insert_after("D", "C")
# I want A,B,C,D,E,F in continuously

结果是...

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-101-e9d4a6a04b21> in <module>()
      6 temp.insert_first("F")
      7 
----> 8 temp.insert_after("D", "C")
      9 
     10 # s1.delete_first()

<ipython-input-96-aa629a206e57> in insert_after(self, element, p)
     71 
     72     def insert_after(self, element, p):
---> 73         new_node = self._Node(element, p.next)
     74         p.next = new_node
     75 #         new_node = self._Node(element, p._next())

AttributeError: 'str' object has no attribute 'next'

insert_after函数怎么了?

1 个答案:

答案 0 :(得分:1)

您无法分配给函数调用,因此您可能想编写

set.seed(24)
m1 <- matrix(rnorm(100 * 1024), nrow = 100, ncol = 1024)

然后,如您在注释中所述,当您应该从列表中传递节点时,传递字符串'C'。您可能应该找到带有p._next = new_node 的节点,并将其传递给方法。 因此,将新方法添加到SList

self._element == 'C'

然后致电

def find(self, value):
    current = self._head
    while current:
        if current._element == value:
            return current
        current = current._next
    return None