剑指Offer 面试题06. 从尾到头打印链表

面试题06. 从尾到头打印链表

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:

输入:head = [1,3,2]
输出:[2,3,1]

解题代码及思路

可以利用栈的特性:先进后出。来完成这个题目,遍历head,遍历到为空为止,然后每一次遍历都取出val,压如栈中。

取出栈时就是到着的。

效率不太高

import sun.security.util.ArrayUtil;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Auther: truedei
 * @Date: 2020 /20-5-6 22:46
 * @Description:
 */
public class TestA {

    static  public int[] reversePrint(ListNode head) {
        Stack<Integer> stack = new Stack<>();
        ListNode newLN = null;
        while ((newLN=head)!=null){
            stack.push(newLN.val);
            head=head.next;
        }

        int[] ints = new int[stack.size()];

        int i = 0;
        while (!stack.empty()){
            ints[i++] = stack.pop();
        }

        return ints;
    }

    public static void main(String[] args) {

        ListNode a = new ListNode(1);
        ListNode b = new ListNode(3);
        ListNode c = new ListNode(2);

        a.next=b;
        b.next=c;


        Long starTime = System.nanoTime(); // 纳秒

        int[] ints = reversePrint(a);
        System.out.println(ints.toString());

        Long endTime = System.nanoTime() ; // 纳秒

        System.out.println("+=用时:"+(endTime - starTime)+"纳秒");

    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

原创文章 218 获赞 4339 访问量 42万+

猜你喜欢

转载自blog.csdn.net/qq_17623363/article/details/105964714