0

我正在用 Python 实现约瑟夫斯圆算法。我对写 prev=Node(0) 和 head=Node(0) 时出现的错误有一点疑问。当我写 head=Node(0) prev=head 时错误被删除。为什么当我写 prev=Node(0) 和 head=Node(0) 时出现错误。

def getJosephusCircle(n, m):
    class Node:
        def __init__(self, data=None, next=None):
            self.setData(data)
            self.setNext(next)
        def setData(self,data):
            self.data=data
        def getData(self):
            return self.data
        def setNext(self,next):
            self.next=next
        def getNext(self):
            return self.next
        def hasNext(self):
            return self.next!=None

    #circular linked list loop
    head=Node(0)
    prev=head
    for i in range(1,n):
        currentNode=Node(i)
        prev.setNext(currentNode)
        prev=currentNode
    prev.setNext(head)
    currentNode=head
    counter=0
    answer=[]
    while currentNode.getNext()!= currentNode:
        counter+=1
        if counter == m:
            counter = 0
            prev.setNext(currentNode.next)
            answer.append(currentNode.getData())
        else:
            prev=currentNode
            currentNode=currentNode.getNext()
    answer.append(currentNode.getData())
    return answer
print(getJosephusCircle(6,3))

显示错误---而 currentNode.getNext()!= currentNode: AttributeError: 'NoneType' object has no attribute 'getNext'

谢谢你

4

0 回答 0