牛客网在线编程专题《剑指offer-面试题5》从尾到头打印链表

版权声明:本文为博主原创文章,欢迎大家转载,但是要注明我的文章地址。 https://blog.csdn.net/program_developer/article/details/82383155

                                            "微信公众号"

                               

题目链接:

https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035?tpId=13&tqId=11156&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目:

解题思路:

用递归方法遍历链表输出。

# -*- coding:utf-8 -*-
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class SingleLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None

    def add(self, data):
        node = ListNode(data)
        if self.head is None:
            self.head = node
            self.tail = node
        else:
            self.tail.next =node
            self.tail = node

    def iter(self):
        if not self.head:
            return
        cur = self.head
        yield cur.val
        while cur.next:
            cur = cur.next
            yield cur.val

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        if listNode is None:
            return []
        return self.printListFromTailToHead(listNode.next) + [listNode.val]

if __name__=="__main__":
    link_list = SingleLinkedList()
    for i in range(5):
        link_list.add(i)

    for node in link_list.iter():
        print("node is {0}".format(node))

    solution = Solution()
    # Python递归实现。
    print(solution.printListFromTailToHead(link_list.head))


运行结果:

Reference:

【1】Python数据结构-链表

猜你喜欢

转载自blog.csdn.net/program_developer/article/details/82383155