利用栈,倒序都可以用栈解决
先将数据一个一个压入栈
然后再一个一个弹出
另外还有一种方法是利用递归,递归其实跟栈类似
方法一:
package printListReversed5;
import java.util.Stack;
public class PrintListReversed5 {
static void printListReversed(ListNode head) {
if (head != null) {
Stack<ListNode> stack = new Stack<>();
while (head != null) {
stack.push(head);
head = head.nextNode;
}
while (!stack.isEmpty()) {
System.out.println(stack.pop().data);
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ListNode headNode = new ListNode();
headNode.data = 1;
headNode.nextNode = null;
ListNode l1 = new ListNode();
l1.data = 2;
ListNode l2 = new ListNode();
l2.data = 3;
headNode.nextNode = l1;
l1.nextNode = l2;
l2.nextNode = null;
printListReversed(headNode);
}
}
class ListNode {
int data;
ListNode nextNode;
}
方法二:
private static void printListReversed(ListNode headNode) {
if (headNode.nextNode!=null) {
printListReversed(headNode.nextNode);
}
System.out.println(headNode.data);
}