java复习之单链表倒着打印
第一种方法,就是我上一篇讲的,将链表反转之后打印,但是这样会破坏链表的结构,再让你倒着打一遍,还得反转,所以还有以下三种思路
使用栈
//利用栈进行单链表的倒叙打印
public static void reserPrint(Node head){
if(head.next==null){
System.out.println("这就是个头!!!");
return;
}
Stack<Node> stack = new Stack<>();
Node temp= head.next;
while (temp!=null){
stack.push(temp);
temp=temp.next;
}
while (stack.size()>0){
System.out.println(stack.pop());
}
}
递归
public void method(Node node){
if(node.next!=null){
method(node.next);
}
System.out.println(node);
}
public void reserPrint2(Node head){
if(head.next==null){
System.out.println("这就是个头!!!");
return;
}
Node temp=head.next;
method(temp);
}
使用数组来做
public void reserPrint3(Node head){
if(head.next==null){
System.out.println("这就是个头!!!");
return;
}
Node[] nodes = new Node[1000];
int n=0;
Node temp= head.next;
while (temp!=null){
nodes[n++]=temp;
temp=temp.next;
}
for(int i=n-1;i>=0;i--){
System.out.println(nodes[i]);
}
}
就是这样,暂时一共4种,有多的欢迎补充,底层原理是数组或者链表的就不要说了-。-