Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

小问题请教 #1

Open
mengruhou opened this issue Jul 26, 2018 · 1 comment
Open

小问题请教 #1

mengruhou opened this issue Jul 26, 2018 · 1 comment

Comments

@mengruhou
Copy link

mengruhou commented Jul 26, 2018

第27行,为什么result不能用append添加链表的值?必须用extend吗?

'''
题目:输入一个链表,从尾到头打印链表每个节点的值
'''

'''
方法一:使用extend,在尾部插入,其实最关键在于[::-1],只不过输入数据多样化,有可能还是集合,所以转成列表
这个方法效率应该还可以,先存入vector,再反转vector
26ms
5512k
'''

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

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        if not listNode:
            return []

        result = []
        while listNode.next is not None:
            result.extend([listNode.val])
            listNode = listNode.next
        result.extend([listNode.val])

        return result[::-1]
@kyuer
Copy link

kyuer commented Aug 27, 2018

extend 接受一个参数,这个参数总是一个 list,并且把这个 list 中的每个元素添加到原 list 中。另一方面,append 接受一个参数,这个参数可以是任何数据类型,并且简单地追加到 list 的尾部。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants