每个节点由val和自身构成,倒序输出val集合
方法一:
遍历节点,用vector、list等集合装起来,然后reverse,然后遍历容器
package com.example.demo.algorithm;
public class ListNode {
private Integer val;
public ListNode next = null;
ListNode(int val) {
this.val = val;
}
public Integer getVal() {
return val;
}
public void setVal(Integer val) {
this.val = val;
}
public ListNode() {
}
@Override
public String toString() {
return "ListNode{" +
"val=" + val +
", next=" + next +
'}';
}
}
遍历
package com.example.demo.jvm;
import com.example.demo.algorithm.ListNode;
import java.util.ArrayList;
import java.util.Comparator;
public class ReverseListNodeTest {
public static ArrayList printListFromTailToHead(ListNode listNode) {
if (listNode == null) return new ArrayList<>();
ArrayList ret = new ArrayList<>();
while(listNode.next != null) {
ret.add(listNode.getVal());
listNode = listNode.next;
}
ret.add(listNode.getVal());
ret.sort(Comparator.reverseOrder());
return ret;
}
public static void main(String[] args) {
ListNode listNode = new ListNode();
listNode.setVal(1);
ListNode next = new ListNode();
next.setVal(20);
listNode.next = next;
next = null;
listNode.next.next = next;
System.out.println(printListFromTailToHead(listNode));
}
}
方法二,利用栈的特性,用栈收集
Stack继承Vector类,它通过五个操作对类 Vector 进行了扩展。 栈是 后进先出的。 栈提供了通常的 push 和 pop 操作,以及取堆栈顶点的 peek 方法、测试堆栈是否为空的 empty 方法、在堆栈中查找项并确定到堆栈顶距离的 search 方法。
| 方法摘要 | |
|---|---|
| boolean | empty() 测试堆栈是否为空。 |
| E | peek() 查看堆栈顶部的对象,但不从堆栈中移除它。 |
| E | pop() 移除堆栈顶部的对象,并作为此函数的值返回该对象。 |
| E | push(E item)把项压入堆栈顶部。 |
| int | search(Object o) 返回对象在堆栈中的位置,以 1 为基数。 |
package com.example.demo.jvm;
import com.example.demo.algorithm.ListNode;
import java.util.ArrayList;
import java.util.Comparator;
public class ReverseListNodeTest {
public static Stack printListFromTailToHead(ListNode listNode) {
if (listNode == null) return new Stack();
Stack stack = new Stack();
while(listNode.next != null) {
ret.push(listNode.getVal());
listNode = listNode.next;
}
ret.add(listNode.getVal());
ret.sort(Comparator.reverseOrder());
return ret;
}
public static void main(String[] args) {
ListNode listNode = new ListNode();
listNode.setVal(1);
ListNode next = new ListNode();
next.setVal(20);
listNode.next = next;
next = null;
listNode.next.next = next;
Stack = (printListFromTailToHead(listNode));
// 打印栈集合
}
}
方法三,利用双端队列收集
一端进,另一端出



