输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
class listNode:
def __init__(self,x):
self.val=x
self.next=None
class Solution:
def printListFromTailToHead(self,listNode):
# if listNode==:
# return None
array=[]
cur=listNode
while(cur): #防止{}
array.append(cur.val)
cur=cur.next
# array.sort(reverse=True)
return array[-1::-1]
if __name__ == '__main__':
Node1=listNode(5)
Node2=listNode(7)
Node3=listNode(1)
Node4=listNode(3)
Node1.next=Node2
Node2.next=Node3
Node3.next=Node4
pro=Solution()
print(pro.printListFromTailToHead(Node1))
print(pro.printListFromTailToHead({}))
java实现
import java.util.ArrayList; import java.util.Random; import java.util.Scanner; import java.util.Stack;
class listNode{
int val;
listNode next=null;
public listNode(int val){
this.val=val;
} } public class Solution { public ArrayList<Integer> printlistFromtailToHead(listNode listNode){
Stack<Integer> stack=new Stack<Integer>();
ArrayList<Integer> aList =new ArrayList<Integer>();
while(listNode!=null){
stack.push(listNode.val);
listNode=listNode.next;
}
while(!stack.isEmpty()){
aList.add(stack.pop());
}
return aList; }
public static String toString(listNode front){
if(front==null)
return "null";
listNode curr=front;
String str="[";
while(curr.next !=null){
str=str+curr.val+',';
curr=curr.next;
}
str+=curr.val+"]";
return str;
} public static void main(String []args){
Random rnd=new Random();
int listCount;
Scanner keyIn=new Scanner(System.in );
System.out.println("please Enter the size of the list:");
listCount=keyIn.nextInt();
listNode front=null,newNode;
for(int i=0;i<listCount;i++){
newNode=new listNode(rnd.nextInt(100));
newNode.next=front;
front=newNode;//单链表在表头插入新节点。
}
Solution pro=new Solution();
System.out.println("Original list:");
System.out.println(pro.toString(front));
ArrayList<Integer> aList;
aList=pro.printlistFromtailToHead(front);
System.out.println("changed to arraylist is:");
System.out.println(aList);
} }
结果:
please Enter the size of the list: 5
Original list: [92,92,65,54,45]
changed to arraylist is: [45, 54, 65, 92, 92]