《剑指offer》Python语言 面试题5:从尾到头打印链表

    写在开头的话:

    当想写这个的时候,发现已经有人做了这个工作了,详情请见Python基础算法/剑指offer,然而依然决定自己写下这个系列,作为算法部分的巩固和提高。在自己写完后会借鉴Python基础算法/剑指offer的代码,如有部分重复,还请见谅。


    这个还是很简单的,单纯贴代码吧。

# -*- coding: UTF-8 -*-.
'''
输入一个链表,从尾到头打印链表每个节点的值。
'''
class Node(object):
    """节点类"""
    def __init__(self, data = -1, next = next):
        self.data = data
        self.next = next

def solveRecursive(nodeHead):
	'Function to solve problem.'
	if not isinstance(nodeHead, Node):
		return
	solveRecursive(nodeHead.next)
	print nodeHead.data,

def solveStack(nodeHead):
	'Function to solve problem.'
	if not isinstance(nodeHead, Node):
		return
	dataStack = []
	while(isinstance(nodeHead, Node)):
		dataStack.append(nodeHead.data)
		nodeHead = nodeHead.next
	while(dataStack):
		print dataStack.pop(),

def test():
	'Test the program.'
	# Recursive
	# test1
	print "test1"
	node5 = Node(5)
	node4 = Node(4, node5)
	node3 = Node(3, node4)
	node2 = Node(2, node3)
	node1 = Node(1, node2)
	solveRecursive(node1)# 5 4 3 2 1
	# test2
	print "\ntest2"
	node1 = Node(1)
	solveRecursive(node1)# 1
	# test3
	print "\ntest3"
	solveRecursive(None)#

	# Loop
	# test1
	print "\ntest1"
	node5 = Node(5)
	node4 = Node(4, node5)
	node3 = Node(3, node4)
	node2 = Node(2, node3)
	node1 = Node(1, node2)
	solveStack(node1)# 5 4 3 2 1
	# test2
	print "\ntest2"
	node1 = Node(1)
	solveStack(node1)# 1
	# test3
	print "\ntest3"
	solveStack(None)#

if __name__ == "__main__":
	#input()
	test()
    list的append和pop都是O(1)的时间效率,因此两个子程序的时间复杂度都是O(n)。

你可能感兴趣的:(剑指offer)