尝试遍历链表两次

时间:2020-09-26 23:31:26

标签: python linked-list

我在使用Python的链表时遇到一些麻烦。对于一个问题,我应该做一些琐事,例如使用链接列表的问答,每个节点都有一个问答。我应该让程序反复遍历该列表,直到每个问题都正确回答了两次。以下代码是我执行此操作的方法。

class trivia(object):

    def __init__(self, question, answer):
        self.question = question
        self.answer = answer
        self.next = None

    def getQuestion(self):
        return self.question

    def getAnswer(self):
        return self.answer

    def getNext(self):
        return self.next

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


class triviaDeck(object):

    def __init__(self):
        self.head = None

    def size(self):
        current = self.head
        count = 0
        while current != None:  # while not at the end of the list
            count += 1
            current = current.getNext()
        return count
    
    def showTrivia(self, pos=None):
        if pos == None:
            pos = self.size() - 1

        if pos < self.size() and pos >= 0:
            current = self.head
            previous = None
            index = 0
            count = 0

            while count != 2:
                print(current.getQuestion())
                answer = input()
                if answer == current.getAnswer():
                    print("Correct")
                    count = count + 1

                if current.getNext() == 2:
                    current = self.head
                else:
                    current = current.getNext()


    def add(self, question, answer):
        temp = trivia(question, answer)
        temp.setNext(self.head)
        self.head = temp


if __name__ == '__main__':

    deck = triviaDeck()

    deck.add("A", "A")
    deck.add("B", "B")
    deck.add("C", "C")

    deck.showTrivia()

当前,这段代码只遍历列表一次,然后退出。

1 个答案:

答案 0 :(得分:1)

对于循环链表:

  • 插入的第一个节点应指向自身
  • 对于其他节点,请调整指针以将新节点插入到头部之后

尝试以下代码:

with(df, tapply(pop, list(region, ifelse(age >=2, '>=2', '<2')), sum))

#         <2 >=2
#SSC21184 404 490
#SSC21185 518 525

也-对于count = 2逻辑:

  • 节点(琐事)对象应具有counter属性,该属性可以计算对该问题的正确答案
  • 如果响应计数器= 2,则从链接列表中删除该节点
  • 删除最后一个节点后,游戏结束