解法1
# -*- 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
l = []
head = listNode
while head:
l.insert(0, head.val)
head = head.next
return l
1、在列表中插入值
(1).append()方法在列表末尾插入元素
sm = ['cat','dog','bat','spider']
sm.append('fox')
print(sm)
#['cat','dog','bat','spider','fox']
(2).insert()方法在列表自定义位置插入元素
sm = ['cat','dog','bat','spider']
sm.insert(2,'fox')
print(sm)
#['cat', 'dog', 'fox', 'bat', 'spider']
2
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
l = list()
while listNode:
l.append(listNode.val)
listNode = listNode.next
return l[::-1]
这个是python的slice notation的特殊用法。
a = [0,1,2,3,4,5,6,7,8,9]
b = a[i:j] 表示复制a[i]到a[j-1],以生成新的list对象
b = a[1:3] 那么,b的内容是 [1,2]
当i缺省时,默认为0,即 a[:3]相当于 a[0:3]
当j缺省时,默认为len(alist), 即a[1:]相当于a[1:10]
当i,j都缺省时,a[:]就相当于完整复制一份a了
b = a[i:j:s]这种格式呢,i,j与上面的一样,但s表示步进,缺省为1.
所以a[i:j:1]相当于a[i:j]
当s<0时,i缺省时,默认为-1. j缺省时,默认为-len(a)-1
所以a[::-1]相当于 a[-1:-len(a)-1:-1],也就是从最后一个元素到第一个元素复制一遍。所以你看到一个倒序的东东。
3
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
from collections import deque
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
if not listNode:
return []
temp = deque()
while listNode:
temp.appendleft(listNode.val)
listNode = listNode.next
return temp
python3 deque(双向队列)
创建双向队列
import collections
d = collections.deque()
append(往右边添加一个元素)
复制代码
import collections
d = collections.deque()
d.append(1)
d.append(2)
print(d)
#输出:deque([1, 2])
复制代码
appendleft(往左边添加一个元素)
复制代码
import collections
d = collections.deque()
d.append(1)
d.appendleft(2)
print(d)
#输出:deque([2, 1])
复制代码
clear(清空队列)
复制代码
import collections
d = collections.deque()
d.append(1)
d.clear()
print(d)
#输出:deque([])
4
// java 递归超简洁版本
public class Solution {
ArrayList<Integer> arrayList=new ArrayList<Integer>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if(listNode!=null){
this.printListFromTailToHead(listNode.next);
arrayList.add(listNode.val);
}
return arrayList;
}
}