package offer;
import java.util.Stack;
public class PrintEndToBegin {
ListNode listNode;
public PrintEndToBegin() {
// 创建链表
createListNode();
}
public static void main(String[] args) {
PrintEndToBegin printEndToBegin = new PrintEndToBegin();
printEndToBegin.printList(printEndToBegin.listNode);
}
void printList(ListNode listNode) {
if(listNode==null)
{
System.out.println("Invalide input!");
return;
}
Stack<ListNode> stack = new Stack<>();
ListNode tmp=listNode;
while(tmp!=null)
{//链表元素从前往后依次进栈
stack.push(tmp);
tmp=tmp.getNext();
}
while(!stack.empty())//判断栈中是否有元素
{//打印输出
System.out.println(stack.pop().getData());
}
}
void createListNode() {
listNode = new ListNode();
listNode.setData(1);
ListNode newer, last;
last = listNode;
for (int i = 0; i < 50; i++) {// 后面再生成50个链表节点
newer = new ListNode();
newer.setDa
java栈实现 倒序打印链表
最新推荐文章于 2021-06-26 15:50:18 发布