单链表逆序输出
程序员文章站
2022-03-22 08:30:31
...
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;
}
}
上一篇: C语言中使用正则表达式