Ab112
Ab112

Reputation: 11

Trying to traverse a linked list twice

I am having some trouble with linked lists in Python. For a problem I am supposed to do trivia like question and answer with linked lists, each node having a question and answer. I am supposed to have the program go through the list over and over until each question is answered correctly twice. The following code is the method I made to do this.

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()

Currently this code just goes through the list once and then exits.

Upvotes: 1

Views: 663

Answers (1)

Mike67
Mike67

Reputation: 11342

For a circular linked list:

  • The first node inserted should point to itself
  • For additional nodes, adjust the pointers to insert the new node after the head

Try this code:

def add(self, question, answer):
    temp = trivia(question, answer)
    if not self.head:   # first node
        self.head = temp
        temp.setNext(self.head)  # single node, loop to itself
     else:  # add node
        temp.setNext(self.head.getNext())  # shift loop
        self.head.setNext(temp) # insert just after head

Also - For the count = 2 logic:

  • The node (trivia) object should have a counter property which counts correct responses to that question
  • If the response counter = 2, remove that node from the linked list
  • When the last node is removed, game over

Upvotes: 1

Related Questions