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

本文介绍了一种数据结构——链表的逆序打印方法,包括使用栈和递归两种实现方式,通过具体代码示例展示了如何从尾到头打印链表的每个节点值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:输入一个链表的头节点,从尾到头反过来打印出每个节点的值,链表节点定义如下:

class Node{
		int value;
		Node next;
		public Node(int value,Node node) {
			this.value=value;
			this.next=node;
		}
	}

思路一:利用栈先进后出的结构,将节点从头到尾存储入栈,再一个一个取出,打印节点值。

思路二:利用递归,每次输入节点值前,先递归节点的next节点,结束条件是节点的next为null。

解法:

import java.util.Stack;

public class PrintList {
	class Node{
		int value;
		Node next;
		public Node(int value,Node node) {
			this.value=value;
			this.next=node;
		}
	}
	public static void main(String[] args) {
		PrintList list=new PrintList();
		Node node7=list.new Node(7, null);
		Node node6=list.new Node(6,node7);
		Node node5=list.new Node(5,node6);
		Node node4=list.new Node(4,node5);
		Node node3=list.new Node(3,node4);
		Node node2=list.new Node(2,node3);
		Node node1=list.new Node(1,node2);
//		printReserve(node1);//非递归
		printReserve2(node1);//递归
	}
	//非递归:利用栈
	private static void printReserve(Node head) {
		Stack<Node> stack=new Stack<>();
		Node node=head;
		while(node!=null){
			stack.push(node);
			node=node.next;
		}
		while(!stack.empty()){
			System.out.println(stack.pop().value);
		}
	}
	//递归
	private static void printReserve2(Node head){
		if(head!=null){
			if(head.next!=null){
				printReserve2(head.next);
			}
			System.out.println(head.value);
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值