从链表尾部打印链表

1、方法一:先将链表逆序,然后在从头遍历
详见http://www.jianshu.com/p/917f96a31098逆序单链表
2、方法二:借助栈,从头遍历单链表,将数据压栈,然后再依次弹出

# 定义一个栈

class SStack(object):
    def __init__(self):
        self.elems = []

    def is_empty(self):
        return self.elems == []

    def push(self, elem):
        self.elems.append(elem)

    def pop(self):
        if self.elems == []:
            print '栈空'
            # 抛出异常
        return self.elems.pop()

    def printall(self):
        for i in range(len(self.elems)):
            print self.pop()

# 节点定义
class LNode(object):
    def __init__(self, elem, _next):
        self.elem = elem
        self.next = _next

# 链表类
class LinkList(object):
    def __init__(self):
        self.head = None

    def append(self, elem):
        if self.head is None:
            self.head = LNode(elem, None)
            return
        
        p = self.head
        
        while p.next is not None:
            p = p.next

        p.next = LNode(elem, None)

    # 直接逆序输出单链表
    def print_all_rev(self):
        my_stack = SStack()
        p = self.head
        while p is not None:
            my_stack.push(p.elem)
            p = p.next
        my_stack.printall()
        

if __name__ == '__main__':
    linkList = LinkList()
    for i in range(100):
        linkList.append(i)
    # 使用栈实现链表的逆序输出
    linkList.print_all_rev()
    

推荐阅读更多精彩内容