如何使用带有节点的堆栈打印实际堆栈?

时间:2019-08-12 18:53:53

标签: python-3.x stack

我正在使用节点实现堆栈。我想打印出堆栈的所有节点,例如:

s.push(4)
s.push('dog')
s.push(6)

当我想打印出堆栈时,输出为:

6
'dog'
4

我应该使用__iter__方法吗?这里有点失落,我只能在不将节点用作数据时打印堆栈。

这是我的代码:

class Node():
    def __init__(self, d):
        self.data = d
        self.next_node = None



class StackNode():

    def __init__(self):
        self.top = None
        self.size = 0

    def push(self, d):
        new_node = Node(d)
        if self.top: #if we have a top node this means that the stack isn't empty
            new_node.next_node = self.top #based on the PUSH operation instructions
            #the next node must be the current top node

        self.top = new_node # otherwise, we will set the new top node to be the new_node
        self.size += 1

    def pop(self):
        #Special case: if top node is none (if stack is empty)
        #we will return none
        if self.top is None:
            return None

        #otherwise
        result = self.top.data #the node thats left in the stack
        self.top = self.top.next_node #self.top is now going to be equal to
        #whatever it's pointing to

        self.size -= 1 #decrementing

        return result


    def peek(self):
        if self.top is None: #if stack empty the top node is none
            return None

        #otherwise

        return self.top.data #top node of stack, the ".data" represemts the Node class
        #and the ".top" represents what is at the top of the Stack class

    def is_empty(self): #couldve used this earlier for checking if stack empty with,
        #special cases
        return self.top is None #the result of the boolean statement is eitehr True/False

        #instead of
        '''
        if self.top is None:
            return True

        return False
        '''

2 个答案:

答案 0 :(得分:0)

尝试此方法:

def __str__(self):
    aux = self.top
    while aux != None:
        print(aux.data)
        aux = aux.next_node

答案 1 :(得分:0)

您可以在类__iter__中实现StackNode方法:

def __iter__(self):
    head = self.top
    while head:
        yield head.data
        head = head.next_node

然后:

s = StackNode()

s.push(4)
s.push('dog')
s.push(6)

for i in s:
    print(i)

将打印:

6
dog
4