逆序打印单向链表

问题:

给你一个单向链表,比如 a -> b -> c -> d -> e -> f, 把这个链表逆序打印出来,即:f -> e -> d ->c ->b ->a

思路:

方法1:遍历链表,把每一个值按照顺序放在一个stack 里,当遍历完毕以后,再把 stack 里的每一个node取出来打印。

方法2:利用递归的原理,先遍历到链表的最后一个节点,然后再打印。这样做本质上和方法1是一样的。

 class Node {
	String value;
	Node next = null;
	
	public Node(String value) {
		this.value = value;
	}
}
public static void reversePrint(Node node) {
	if (node == null) return;
	if (node.next != null) {
		reversePrint(node.next);
	}
	
	System.out.println(node.value);
}

如果顺序打印,方法为:

public static void printList(Node node) {
	if (node == null) return;
	System.out.println(node.value);
	if (node.next != null) {
		printList(node.next);
	}
}

public static ListNode reverse(ListNode head) {
	if (head == null) return null;
	
	ListNode n = head.next;
	ListNode previous = head;
	head.next = null;
	while(n != null) {
		ListNode nn = n.next;
		n.next = previous;
		previous = n;
		n = nn;
	}
	return previous;
}

转载请注明出处:http://blog.csdn.net/beiyetengqing



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值