剑指Offer面试题6:从尾到头打印链表

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;
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值