从尾部到头部逆向打印单链表,有以下两种方法:
1、借助“栈”打印
2、借助递归函数
定义链表节点数据结构:
from random import randint class Node: def __init__(self,val): self.val=val self.next=None @classmethod def init_random_list(cls,count): ''' 初始化长度为count的随机链表 ''' head=Node(randint(0,100)) pre=head for i in range(count-1): node=Node(randint(0,100)) pre.next=node pre=node return head @classmethod def print(cls,head): ''' 打印链表 ''' result=[] while(head!=None): result.append(str(head.val)) head=head.next print(','.join(result))
待实现的方法:
def reverse(head:Node): pass
测试结果:
ori_list=Node.init_random_list(10) print('before reverse:') Node.print(ori_list) new_list=reverse(ori_list) print('after reverse:') Node.print(new_list)期望的打印结果样例:
before reverse: 16,75,70,20,67,72,98,34,100,63 after reverse: 63,100,34,98,72,67,20,70,75,16
接下来我们具体实现:
1、借助“栈”打印
2、借助递归函数