从尾到头打印链表
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);
}
}