題目描述:輸入一個鏈表的頭結(jié)點(diǎn),從尾到頭反過來打印出每個結(jié)點(diǎn)的值芜果。
目的:體會遞歸和非遞歸算法
代碼:
package com.guanstudy;
import java.util.Stack;
/**
- @date 2018年4月9日
- @author junpu.guan
- @Description: TODO
**/
public class Test {
public static void main(String[] args){
ListNode node1=new ListNode();
ListNode node2=new ListNode();
ListNode node3=new ListNode();
node1.setData(1);
node2.setData(2);
node3.setData(3);
node1.setNext(node2);
node2.setNext(node3);
printListReverse(node1);
}
//遞歸
public static void printListReverseRecursive(ListNode head){
if(null!=head){
if(null!=head.getNext()){
printListReverseRecursive(head.getNext());
}
}
System.out.println(head.getData());
}
//非遞歸
public static void printListReverse(ListNode head){
Stack<ListNode> stack = new Stack<ListNode>();
while(null!=head){
stack.push(head);
head = head.getNext();
}
while(!stack.isEmpty()){
System.out.println(stack.pop().getData());
}
}
}
·