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

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

面试题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);
    }
}

运行结果

3
2
1

3
2
1
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容