剑指Offer6-从尾到头打印链表

题目:
输入一个链表的头节点,从尾到头反过来打印出每个节点的值。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
class ListNode():
    def __init__(self, value, next=None):
        self.val = value
        self.next = next


def PrintListReversingly(head):
    stcak=[]
    while head is not None:
        stcak.append(head.val)
        head = head.next
    while stcak:
        print(stcak.pop())
    print('finish!')


array = [1, 2, 3, 4, 5]
head = ListNode(array[0])    # 用于链接整个链表的头节点
head_0 = head                # 后续调用的头节点
for i in range(len(array)-1):
    current_node = ListNode(array[i+1])
    head.next = current_node
    head = head.next

PrintListReversingly(head_0)


# 输出结果为:
# 5
# 4
# 3
# 2
# 1
# finish!

你可能感兴趣的:(笔试+面试)