java栈实现 倒序打印链表

来源:互联网 发布:数据存储解决方案 nas 编辑:程序博客网 时间:2024/06/06 03:17
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;}}