剑指offer第二版-6.从尾到头打印链表

本系列导航:剑指offer(第二版)java实现导航帖

面试题6:从尾到头打印链表

题目要求:
如题

package structure;
/**
 * Created by ryder on 2017/6/13.
 *
 */
public class ListNode {
    public T val;
    public ListNode 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 node){
        if(node==null)
            return;
        else{
            printReversinglyRecursively(node.next);
            System.out.println(node.val);
        }
    }
    //非递归版
    public static void printReversinglyIteratively(ListNode node){
        Stack stack = new Stack<>();
        for(ListNode 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 head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        printReversinglyRecursively(head);
        System.out.println();
        printReversinglyIteratively(head);
    }
}

运行结果

3
2
1

3
2
1

你可能感兴趣的:(剑指offer第二版-6.从尾到头打印链表)