剑指offer—从尾到头打印链表

题目:输入一个链表的头节点,按链表从尾到头的顺序返回每个节点的值(用数组返回)。 如输入{1,2,3}的链表如下图:
在这里插入图片描述
返回一个数组为[3,2,1]

0 <= 链表长度 <= 10000

参考链接
  链表的输入输出代码
  python 链表
  python 链表实现 单链表
  python maximum recursion depth exceeded解决方式
其实参考了很多,但是这几个是用处较大的

题目开始先定义链表的元素,一个是val也就是链表需要存储的值elem,另外一个next则是链表存放下一个结点的位置

class ListNode:
    def __init__(self, elem):
        self.val = elem
        self.next = None

然后看开始编写输出的函数

class Solution:
# 方法一
    def printListFromTailToHead1(self, listNode):  # 将链表的内容倒序输出,listNode为链表的头指针
        if not listNode:
            return None
        temp = []
        fuck = []
        while listNode:
            temp.append(listNode.val)
            listNode = listNode.next
        while temp:
            fuck.append(temp.pop())
        return fuck
#  方法二
    def printListFromTailToHead2(self, listNode):  # 从头到尾遍历,然后逆序输出
        result = []
        while listNode:
            result.append(listNode.val)
            listNode = listNode.next
        return result[::-1]  # 将数组倒序输出,也可以使用result.reverse()

第三种方法采用递归的方式,之所以将其单独写,是因为递归这玩意有深度限制,会出现maximum recursion depth exceeded的错误,参考了一些大佬的解决方法后,修改后代码如下:

import sys

sys.setrecursionlimit(1000000)
class Solution: # 需要的内存比前两种方法要多出很多,一般解题有空间限制的话不建议
    def printListFromTailToHead2(self, listNode):  # 递归方法求逆输出
        result = []
        def readlist(node):
            if node:
                readlist(node.next)
                result.append(node.val)
        readlist(listNode)
        return result

  正经的代码写完了,现在来谈一谈写代码时遇到的较为折磨人的问题,因为牛客网给的编辑器并没有输入的地方,我只能编写核心的地方,因此自己进行测试成了大问题(没接触过python的链表),自测的时候不知道该如何输入一个链表,查阅资料以后会输入链表以后,又不知道怎么将这个链表放到写好的输出函数里去执行,几经波折,才想通只要把链表头给函数就行了,于是就有了下面的代码(其中大部分代码是照着大佬的打出来的),了解了原理以后实现链表的增删改还是很容易的,写了三四天,一直想不通怎么把链表放入函数之中,感觉这三四天的精华都集中于那个返回链表头指针的函数里吧

class SingleLinkList(object):
    def __init__(self, node=None):
        self.__head = node

    def is_empty(self):  # 判断链表是否为空
        return self.__head is None

    def findhead(self):  # 返回链表的头部地址
        return self.__head

    def length(self):  # 判断链表的长度
        cur = self.__head
        count = 0  # 链表长度
        while cur is not None:  # cur游标,用来遍历节点,count记录数量
            count += 1
            cur = cur.next
        return count

    def travel(self):  # 遍历链表
        cur = self.__head
        while cur is not None:
            print(cur.val, end='->')
            cur = cur.next
        # print('')

    def append_head(self, item):  # 在链表的头部添加节点
        node = ListNode(item)
        node.next = self.__head
        self.__head = node

    def append_tail(self, item):  # 在链表的尾部添加节点
        node = ListNode(item)
        if self.is_empty():
            self.__head = node
        else:
            cur = self.__head
            while cur.next is not None:
                cur = cur.next
            cur.next = node

    def append(self, pos, item):  # 在链表的任意位置添加节点
        if pos <= 0:
            self.append_head(item)
        elif pos > (self.length() - 1):
            self.append_tail(item)
        else:
            cur = self.__head
            count = 0
            while count < (pos - 1):
                count += 1
                cur = cur.next
            node = ListNode(item)
            node.next = cur.next
            cur.next = node

    def remove(self, item):  # 删除链表的指定元素
        cur = self.__head
        pre = None
        while cur is not None:
            if cur.val == item:
                if cur == self.__head:
                    self.__head = cur.next
                else:
                    pre.next = cur.next
                break
            else:
                pre = cur
                cur = cur.next

    def search(self, item):  # 查找元素是否在链表中
        cur = self.__head
        while cur is not None:
            if cur.val == item:
                return True
            else:
                cur = cur.next
        return False

    def where(self, item):  # 查找元素在链表的哪个位置
        cur = self.__head
        count = 0
        while cur is not None:
            if cur.val == item:
                return count + 1
            else:
                cur = cur.next
                count += 1
        return False

这题对于我这C语言链表学的都不怎么样的人来说简直就是噩梦

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值