我的任务是以不同的方式打印堆栈和队列
我实现了单链表堆栈和双链表队列
这是我将元素推入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、2、3、4、5、6、7、8、9、10”时,期望“9 6 14 22 5 5”作为输出是没有意义的
使用打印方法不是最佳做法。打印是一个应该与堆栈/队列实现逻辑分开的问题。而是定义一个迭代列表中的值的方法,例如通过实现
__iter__
,如果需要格式化字符串__str__
或__repr__
如果一个函数对于不同类的实例表现不同,那么最好在每个类上分别定义它
这里是一个实现的想法,其中
Queue
继承自Stack
。由于我不理解打印“#”符号的逻辑,因此我将使用“>;”,这样,朝向列表的箭头表示将添加未来值的一侧,而远离列表的箭头表示将从列表中删除值的一侧由于}的
Queue
继承自Stack
,因此两个类的添加/删除值的方法都称为insert
和extract
Queue
重写{insert
实现,将FILO更改为FIFO逻辑相关问题 更多 >
编程相关推荐