从尾到头打印链表

本文介绍了一种数据结构——链表的逆序打印方法,主要通过两种方式实现:使用栈和递归。栈是一种先进后出的数据结构,适用于需要逆序处理元素的场景;而递归则提供了一种更简洁的代码实现方式。

从尾到头打印链表

1.使用数据结构栈 stack ,栈是一种先进后出的数据结构,所以遍历链表,将其依次入栈,最后全部出栈即可。

//使用栈的数据结构
	public static void Sys(node head) {
		Stack st=new Stack();
		
		//从头入栈
		while(head!=null) {
			System.out.println("入栈"+head.value);
			st.push(head);
			head=head.next;
			
		}
		
		//从尾输出栈
		while (!st.isEmpty()) {
			node temp =(node) st.pop();
			System.out.println( "逆序输出"+temp.value);
			
			
		}
		
		
	}

2.使用递归,只要head还有next,就可以继续执行该函数,直到执行到尾部,然后再依次执行输出语句,使用递归调用,代码更加简洁

//使用递归
	public static void userecursion(node head) {
		if(head.next!=null) {
			userecursion(head.next);
		}
		System.out.println(head.value);
	}
}

输出结果测试
在这里插入图片描述在这里插入图片描述

源代码

import java.util.Stack;

/**
 * 
 */

/***
 * @author 18071
 * @Date 2019年2月19日
 * 功能: 从尾到头打印链表节点
 ***/
public class text {
	static node tn=new node(1);
	static node head=tn;
	public static void main(String args[]) {
		for(int i=2;i<=5;i++)
		{
		  
		   System.out.println("建立链表节点"+tn.value);
		   tn.setnext(i);
		   tn=tn.next;
		   
		}
		System.out.println(tn.value);
		System.out.println("head is "+head.value);
		
		Sys(head);
		
		//userecursion(head);
		
		
	 
	}

	//使用栈的数据结构
	public static void Sys(node head) {
		Stack st=new Stack();
		
		//从头入栈
		while(head!=null) {
			System.out.println("入栈"+head.value);
			st.push(head);
			head=head.next;
			
		}
		
		//从尾输出栈
		while (!st.isEmpty()) {
			node temp =(node) st.pop();
			System.out.println( "逆序输出"+temp.value);
			
			
		}
		
		
	}

	
	//使用递归
	public static void userecursion(node head) {
		if(head.next!=null) {
			userecursion(head.next);
		}
		System.out.println(head.value);
	}
}


class node{
	public int value;
	public node next;
	node(int x){
		this.value=x;
		this.next=null;
	}
	public void setnext(int n) {
		next=new node(n);
		
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值