题目描述 输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
add
方法首位插入/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.ArrayList;
public class Solution {
ArrayList<Integer> list=new ArrayList<>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
while (listNode!=null) {
list.add(0,listNode.val);
listNode=listNode.next;
}
return list;
}
}
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.ArrayList;
public class Solution {
ArrayList<Integer> list=new ArrayList<>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if (listNode!=null) {
printListFromTailToHead(listNode.next);
list.add(listNode.val);
}
return list;
}
}
# -*- 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
stack = []
result = []
while listNode:
stack.append(listNode.val)
listNode = listNode.next
while stack:
result.append(stack.pop())
return result
# -*- 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
list = []
def fun(Node):
if Node:
fun(Node.next)
list.append(Node.val)
fun(listNode)
return list
# -*- 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
list = []
while listNode:
list.append(listNode.val)
listNode=listNode.next
return list[::-1]
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def __init__(self):
self.list=[]
def printListFromTailToHead(self, listNode):
if listNode:
if listNode.next:
self.printListFromTailToHead(listNode.next)
self.list.append(listNode.val)
return self.list