在Python中使用相同的函数以不同的方式打印堆栈或行

2024-06-17 13:10:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我的任务是以不同的方式打印堆栈和队列

我实现了单链表堆栈和双链表队列

这是我将元素推入Stog(堆栈)和Red(队列)的主要功能

stavi函数与enqueue相同,这是在队列类中

def stavi(self, data):

        if self.head == None:
            self.head = Node(data)

        else:
            newnode = Node(data)
            newnode.next  = self.head
            self.head = newnode

我不能改变主要部分

L = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 
S = Stog() 
R = Red() 
for element in L: 
   R.stavi(element)

这就是我如何调用函数ispis(打印):

ispis(S)
ispis(R)

这就是我制作函数ispis的方法:

def ispis(self):
 
    
    current = self.head
    if (self.head == None):
        print ("Lista je prazna")
        return

    print("<-- ", end= "")
    while(current != None):
        if (current.next is None):
            print(current.data)
        else:
            print (current.data, end = ", ")
        current = current.next
    return

结果应该是:

互联网供应商信息系统<;——961412255

ispis(R)#10 9 8 7 6 5 4 3 2 1-->

我的结果是:

<;——9,6,14,22,5,5

<;——1,2,3,4,5,6,7,8,9,10

我知道如何为堆栈创建它,但我的代码如何“理解”堆栈和队列之间的差异。或者我应该从尾部在队列中添加元素吗


1条回答
网友
1楼 · 发布于 2024-06-17 13:10:50

所提供信息中的一些问题:

  • 不需要实现带有双重链表的队列。您只需要一个单链表,但它的头部和尾部都有引用

  • 您的代码只填充队列,而不是堆栈

  • 当输入为“1、2、3、4、5、6、7、8、9、10”时,期望“9 6 14 22 5 5”作为输出是没有意义的

  • 使用打印方法不是最佳做法。打印是一个应该与堆栈/队列实现逻辑分开的问题。而是定义一个迭代列表中的值的方法,例如通过实现__iter__,如果需要格式化字符串__str____repr__

  • 如果一个函数对于不同类的实例表现不同,那么最好在每个类上分别定义它

这里是一个实现的想法,其中Queue继承自Stack。由于我不理解打印“#”符号的逻辑,因此我将使用“>;”,这样,朝向列表的箭头表示将添加未来值的一侧,而远离列表的箭头表示将从列表中删除值的一侧

class Node:
    def __init__(self, value, nxt=None):
        self.value = value
        self.next = nxt
    
class Stack:
    def __init__(self, values=None):
        self.head = None
        if values:
            self.insert(*values)

    def insert(self, *values):
        for value in values:
            self.head = Node(value, self.head)

    def extract(self):
        if self.head:
            value = self.head.value
            self.head = self.head.next
            return value

    def __iter__(self):
        node = self.head
        while node:
            yield node.value
            node = node.next

    def join(self):
        return " ".join(map(str, self)) or "(empty)"

    def __str__(self):
        return "< > " + self.join()

class Queue(Stack):
    def __init__(self, values=None):
        self.tail = None
        super().__init__(values)

    def insert(self, *values):
        if values and not self.tail:
            self.head = self.tail = Node(values[0])
            values = values[1:]
        for value in values:
            self.tail.next = self.tail = Node(value)

    def __str__(self):
        return "<  " + self.join() + " < "

values = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
s = Stack(values)
q = Queue(values)

print("Stack", s)
print("Queue", q)

由于Queue继承自Stack,因此两个类的添加/删除值的方法都称为insertextractQueue重写{}的insert实现,将FILO更改为FIFO逻辑

相关问题 更多 >