【剑指Offer】3.从尾到头打印链表(Java)

题目描述:输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
package Algorithm.Offer.T3;

import Algorithm.common.ListNode;
import Algorithm.common.ListNodeUtil;

import java.util.ArrayList;
import java.util.Stack;

/**
 * 从尾到头打印链表值
 *
 * @author wangfei
 */
public class Solution {
    /**
     * 利用栈先进后出原则进行倒序打印
     *
     * @param listNode
     * @return
     */
    public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        Stack<Integer> stack = new Stack<>();
        while (listNode != null) {
            stack.push(listNode.val);
            listNode = listNode.next;
        }
        ArrayList<Integer> list = new ArrayList<>();
        while (!stack.isEmpty()) {
            list.add(stack.pop());
        }
        return list;
    }

    /**
     * 利用动态数组的性质将链表元素从头到尾依次添加到动态数组索引为0的位置,这样最后添加进
     * 来的元素放在首位,第一个添加进来的元素则放在末尾,也就实现了倒序
     *
     * @param listNode
     * @return
     */
    public static ArrayList<Integer> printListFromTailToHead2(ListNode listNode) {
        ArrayList<Integer> list = new ArrayList<>();
        if (listNode == null)
            return list;
        list.add(0, listNode.val);
        ListNode temp = listNode.next;
        while (temp != null) {
            list.add(0, temp.val);
            temp = temp.next;
        }
        return list;
    }

    public static void main(String[] args) {
        long start = System.nanoTime();
        ListNodeUtil listNodeUtil = new ListNodeUtil();
        int[] arr = {1, 2, 3, 4, 5};
        ListNode listNode = listNodeUtil.buildListNode(arr);
        System.out.println(printListFromTailToHead(listNode));
        long end = System.nanoTime();
        System.out.println("运行时间:" + (end - start) + "ns");
    }
}
package Algorithm.common;

/**
 * ListNode工具类,实现创建链表
 *
 * @author wangfei
 */
public class ListNodeUtil {
    /**
     * 尾插法创建链表
     *
     * @param input
     * @return
     */
    public static ListNode buildListNode(int[] input) {
        if (input.length == 0)
            return null;
        ListNode head = new ListNode(input[0]);
        ListNode currentNode = head;
        for (int i = 1; i < input.length; i++) {
            currentNode.next = new ListNode(input[i]);
            currentNode = currentNode.next;
        }
        return head;
    }
}

public class ListNode {
    public int val;
    public ListNode next;

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值