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.setData(i);
last.setNext(newer);
last = newer;
}
}
}
package offer;
public class ListNode {
ListNode next;
int data;
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
}