从尾到头打印链表

2018-05-08  本文已影响0人  twilight_mao

https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035?tpId=13&tqId=11156&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目描述

输入一个链表,从尾到头打印链表每个节点的值。

思路

1.熟悉链表ListNode


分析.jpg

2.反转ArrayList可用Collections.reverse(list);
3.在此回忆一下数组与链表的区别:

代码

public class Solution {
    public static class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }

    public static void main(String[] args) {
        int[] input = new int[]{67, 0, 24, 58};
        ListNode listNode = buildListNode(input);
        ArrayList list = printListFromTailToHead(listNode);
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }

    public static ListNode buildListNode(int[] input) {
        ListNode head = new ListNode(-1);
        ListNode p = head;
        for (int i = 0; i < input.length; i++) {
            ListNode n = new ListNode(input[i]);
            p.next = n;
            p = p.next;
        }
        return head.next;
    }

    public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        ListNode n = listNode;
        while (n != null) {
            list.add(n.val);
            n = n.next;
        }
        Collections.reverse(list);
        return list;
    }
}
上一篇下一篇

猜你喜欢

热点阅读