本系列導(dǎo)航:劍指offer(第二版)java實(shí)現(xiàn)導(dǎo)航帖
面試題6:從尾到頭打印鏈表
題目要求:
如題
package structure;
/**
* Created by ryder on 2017/6/13.
*
*/
public class ListNode<T> {
public T val;
public ListNode<T> next;
public ListNode(T val){
this.val = val;
this.next = null;
}
@Override
public String toString() {
StringBuilder ret = new StringBuilder();
ret.append("[");
for(ListNode cur = this;;cur=cur.next){
if(cur==null){
ret.deleteCharAt(ret.lastIndexOf(" "));
ret.deleteCharAt(ret.lastIndexOf(","));
break;
}
ret.append(cur.val);
ret.append(", ");
}
ret.append("]");
return ret.toString();
}
}
package chapter2;
import structure.ListNode;
import java.util.Stack;
/**
* Created by ryder on 2017/6/13.
* 從尾到頭打印鏈表
*/
public class P58_PrintListInReversedOrder {
//遞歸版
public static void printReversinglyRecursively(ListNode<Integer> node){
if(node==null)
return;
else{
printReversinglyRecursively(node.next);
System.out.println(node.val);
}
}
//非遞歸版
public static void printReversinglyIteratively(ListNode<Integer> node){
Stack<Integer> stack = new Stack<>();
for(ListNode<Integer> temp=node;temp!=null;temp=temp.next)
stack.add(temp.val);
while(!stack.isEmpty())
System.out.println(stack.pop());
}
public static void main(String[] args){
ListNode<Integer> head = new ListNode<Integer>(1);
head.next = new ListNode<Integer>(2);
head.next.next = new ListNode<Integer>(3);
printReversinglyRecursively(head);
System.out.println();
printReversinglyIteratively(head);
}
}
運(yùn)行結(jié)果
3
2
1
3
2
1