如题 (总结)
借鉴学习文章列表
- 链接1:
- 链接2:
- ALiBaBaJavaCodingGuideLines
1.ListNode
public class ListNode {
int val;
ListNode next = null;
public ListNode() {
}
ListNode(int val) {
this.val = val;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
public void setVal(int val) {
this.val = val;
}
}
2. Solution代码
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if(listNode==null){
return new ArrayList<>();
}
Stack<Integer> stack = new Stack<>();
ListNode t = listNode;
while (t!=null){
stack.push(t.val);
t = t.next;
}
ArrayList<Integer> arrayList = new ArrayList<>(stack.size());
while(!stack.empty()){
arrayList.add(stack.pop());
}
return arrayList;
}
}
3.Test测试
public class Test {
public static void main(String[] args) {
ListNode listNode = new ListNode();
int arr[] = {67,0,24,58};
ListNode next =listNode;
for(int i : arr){
next.setVal(i);
//注意, 面向题解答案编程后发现, 最后的链表末尾是不设置结点的!坑!
if(i!=58){
next.setNext(new ListNode());
next = next.getNext();
}
}
Solution solution = new Solution();
ArrayList<Integer> arrayList = solution.printListFromTailToHead(listNode);
for(Integer i: arrayList){
System.out.println(i+" ");
}
}
}
测试结果
58
24
0
67