剑指offer E5 倒序打印链表


/**
 * 题目:输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
 * 思路:1)从头到尾遍历,并改变链表顺序
 *      2)用栈实现后进先出
 */
public class E5 {
    public static void main(String[] args) {
        //int a[] = new int[]{1,2,3,4,5,6,7,8,9,10};
        int a[] = new int[]{};
        Node head = createLinkFromArray(a);
        printListReversingly(head);
    }

    private static void printListReversingly(Node head) {
        if (head == null) return;
        Stack<Node> stack = new Stack<>();
        Node currentNode = head;
        while (currentNode != null) {
            stack.push(currentNode);
            currentNode = currentNode.getNext();
        }
        while (!stack.isEmpty()) {
            System.out.print(stack.pop().getKey()+" ");
        }
    }

    private static Node createLinkFromArray(int[] a) {
        if (a==null || a.length ==0) {
            return null;
        }
        Node head = new Node(a[0]);
        Node current = head;
        for (int i=1;i<a.length;i++) {
            current.setNext(new Node(a[i]));
            current = current.getNext();
        }
        return head;
    }


}

class Node {
    private int key;
    private Node next;

    public Node(){}

    public Node(int key) {
        this.key = key;
    }

    public Node(int key, Node next) {
        this.key = key;
        this.next = next;
    }

    public int getKey() {
        return key;
    }

    public void setKey(int key) {
        this.key = key;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值