題目:輸入一個鏈表的頭結(jié)點卧斟,從尾到頭反過來打印出每個結(jié)點的值。
Java代碼如下:
package demo;
import java.util.Stack;
public class TestList {
/**
* 結(jié)點對象
*/
public static class ListNode {
int val; // 結(jié)點的值
ListNode next; // 下一個結(jié)點
}
/**
* 循環(huán)打印單鏈表怎虫,然后使用棧輸出
*/
public static void printListInverselyUsingIteration(ListNode root) {
Stack<ListNode> stack = new Stack<>();
while(root != null) {
stack.push(root);
root = root.next;
}
ListNode tmp = null;
while(!stack.isEmpty()) {
tmp = stack.pop();
System.out.println(tmp.val + " ");
}
}
/**
* 使用遞歸
*/
public static void printListInverselyUsingRecursion(ListNode root) {
if(root != null) {
printListInverselyUsingRecursion(root.next);
System.out.println(root.val + " ");
}
}
public static void main(String[] args) {
ListNode root = new ListNode();
root.val = 1;
root.next = new ListNode();
root.next.val = 2;
root.next.next = new ListNode();
root.next.next.val = 3;
root.next.next.next = new ListNode();
root.next.next.next.val = 4;
root.next.next.next.next = new ListNode();
root.next.next.next.next.val = 5;
printListInverselyUsingIteration(root);
System.out.println("*******");
printListInverselyUsingRecursion(root);
}
}