public class Reverse{
public static void main(String[] args) {
Node root=build(5);;
Node node=root;
while(node!=null){
System.out.print(node.value+" ");
node=node.next;
}
System.out.println();
reversePrint(root);
System.out.println();
reversePrint2(root);
}
//构造固定长度的链表
public static Node build(int len){
Node head=new Node();
Random r=new Random();
head.value=r.nextInt(100);
Node tmp=head;
while((len--)!=1){
Node node=new Node();
node.value=r.nextInt(100);
tmp.next=node;
tmp=node;
}
return head;
}
//递归方式逆序
public static void reversePrint(Node node){
if(node==null){
return;
}
reversePrint(node.next);
System.out.print(node.value+",");
}
//栈逆序输出
public static void reversePrint2(Node node){
Stack<Node> s=new Stack<Node>();
while(node!=null){
s.push(node);
node=node.next;
}
while(!s.isEmpty()){
Node n=(Node) s.pop();
System.out.print(n.value+",");
}
}
private static class Node{
int value;
Node next;
}
}
单链表逆序输出
原文作者:linkingfei
原文地址: https://blog.csdn.net/linkingfei/article/details/82291011
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/linkingfei/article/details/82291011
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。