package offer;
import java.util.Stack;
class ListNode{
int m_nKey;
ListNode m_pNext;
public ListNode(int m_nKey) {
this.m_nKey = m_nKey;
}
}
public class Offer06 {
//使用栈
public static void printListReversingly_Iteratively(ListNode pHead) {
Stack<ListNode> nodes = new Stack<ListNode>();
ListNode pNode = pHead;
//循环遍历链表并压入栈
while(pNode != null) {
nodes.push(pNode);
pNode = pNode.m_pNext;
}
//打印栈里的东西
while (!nodes.empty()) {
pNode = nodes.pop();
System.out.println(pNode.m_nKey);
}
}
//使用递归函数
public static void printListReversingly_Recursively(ListNode pHead) {
if (pHead != null) {
//if (pHead.m_pNext != null) {
printListReversingly_Recursively(pHead.m_pNext);
// }
System.out.println(pHead.m_nKey);
}
}
public static void main(String[] args) {
ListNode node1 = createListNode();
//printListReversingly_Iteratively(node1);
printListReversingly_Recursively(node1);
}
public static ListNode createListNode() {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
ListNode node5 = new ListNode(5);
node1.m_pNext = node2;
node2.m_pNext = node3;
node3.m_pNext = node4;
node4.m_pNext = node5;
return node1;
}
}