java 反向打印链表_python中反向/反向打印链表的方法

我认为您的问题是由于这样一个事实:没有一种有效的方法可以在单链链表上向后迭代。在

我通过使用一些神奇的方法(又称dunder方法)稍微增强了代码:其名称(通常)以双下划线开头和结尾的方法。您可以在Special method names下的文档中阅读有关它们的信息。在

当对象被传递给str内置函数时,对象的__str__方法将被调用(当您试图打印对象时,这是隐式发生的)。如果一个对象没有__str__方法,则调用它的__repr__方法;通常最好至少定义这两个方法中的一个,否则当您试图打印对象时,将调用从泛型object继承的默认__repr__方法。在

我已经将您的getSize方法改为__len__,当一个对象传递给len内置函数时,将调用该方法。在

当对象的__iter__方法被传递给iter内置函数时,无论是显式的,还是在某种for循环中试图迭代对象时,或者当您将其传递给list或类似的构造函数时,都会调用该方法。它通常与__next__方法一起工作,该方法在python2中被命名为next。当一个对象具有这些方法时,以各种方式对其进行迭代就相对容易了。在

要进行反向打印,我们只需将实例传递给list,并将结果列表传递给reversed,后者返回一个迭代器,该迭代器向后迭代其list参数。在

下面的代码是为python2编写的;对于python3,将next方法改为__next__。在class Node(object):

def __init__(self, data=None, nextNode=None):

self.data = data

self.nextNode = nextNode

def __str__(self):

return str(self.data)

class LList(object):

def __init__(self):

self.head = None

self.current = None

self.size = 0

def insert(self, node):

if self.head is not None:

# set new node's pointer to old head

node.nextNode = self.head

self.head = node

self.size += 1

def __len__(self):

return self.size

def __iter__(self):

self.current = self.head

return self

def next(self):

current = self.current

if current is None:

raise StopIteration

else:

self.current = current.nextNode

return current

def printLL(self):

for i, node in enumerate(self, 1):

print(node, i)

# print the list backwards

def reverse_print(self):

c = len(self)

for node in reversed(list(self)):

print(node, c)

c -= 1

# main program

mylist = LList()

mylist.insert(Node("NJ"))

mylist.insert(Node("NR"))

mylist.insert(Node("OH"))

print(len(mylist))

# print forwards

mylist.printLL()

#print the nodes using a list comprehension

print([str(node) for node in mylist])

#print in reverse

mylist.reverse_print()

输出

^{pr2}$

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值