从尾到头打印链表

来源:互联网 发布:查了啊网络电视直播 编辑:程序博客网 时间:2024/04/27 13:22
package com.a.b;import java.util.Stack;public class BackForwardPrintList {public static void main(String[] args) {ListNode pHead = null;pHead = create(pHead);System.out.println("printListReversinglyIteratively");printListReversinglyIteratively(pHead);System.out.println("\nprintListReversinglyRecursively");printListReversinglyRecursively(pHead);}/** * 创建链表 *  * @param pHead * @return */private static ListNode create(ListNode pHead) {for (int i = 0; i < 10; i++) {ListNode node = new ListNode();node.key = i;node.pNext = pHead;pHead = node;}return pHead;}/** * 用循环的方式从后向前打印 *  * @param pHead */private static void printListReversinglyIteratively(ListNode pHead) {if (pHead == null) {return;}Stack<ListNode> nodes = new Stack<ListNode>();ListNode pNode = pHead;while (pNode != null) {nodes.push(pNode);pNode = pNode.pNext;}while (!nodes.empty()) {pNode = nodes.pop();System.out.print(pNode.key + "\t");}}/** * 用递归的方式从后向前打印 *  * @param pHead */private static void printListReversinglyRecursively(ListNode pHead) {if (pHead != null) {printListReversinglyRecursively(pHead.pNext);System.out.print(pHead.key + "\t");}}}/** * 链表节点 * @author Administrator * */class ListNode {int key;ListNode pNext;}

0 0