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種,有多的歡迎補充,底層原理是數組或者鏈表的就不要說了-。-