[剑指offer刷题06] - 从尾到头打印链表

题目[题目及部分解法来自LeeCode]

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
solution one:
先找出链表长度,之后依次向数组末尾添加元素【这也是数组逆置的一种方法!】
    public static int[] reversePrint1(ListNode head) {
        if(head == null)
        {
            int[] arr = new int[0];
            return arr;
        }
        ListNode temp = head;
        int len = 0;
        while(temp.next != null)
        {
            temp = temp.next;
            ++len;
        }
        temp = head;
        System.out.println(len);
        int[] arr = new int[len];
        while(temp.next != null)
        {
            arr[len - 1] = temp.val;
            temp = temp.next;
            --len;
        }
        return arr;
    }
solution two:
先将链表倒置,之后依次添加到数组中。
    public static int[] reversePrint3(ListNode head){
        if(head == null)
        {
            int[] arr = new int[0];
            return arr;
        }
        ListNode temp = head;
        ListNode temp1 = head.next;
        ListNode temp2;
        temp.next = null;
        int counter = 1;
        int arrIndex = 0;
        while(temp1.next != null){
            temp2 = temp1.next;
            temp1.next = temp;
            temp = temp1;
            temp1 = temp2;
            ++counter;
        }
        int[] arr = new int[counter];
        while(temp != null)
        {
            arr[arrIndex] = temp.val;
            ++arrIndex;
            temp = temp.next;
        }
        return arr;
    }
solution three:
利用栈先进后出的特性,将链表元素先依次全部压入栈中,再依次取出添加进数组中。
    public static int[] reversePrint4(ListNode head){
        Stack<ListNode> stack = new Stack<ListNode>();
        ListNode temp = head;
        while(temp.next != null)
        {
            stack.push(temp);
            temp = temp.next;
        }
        int size = stack.size();
        int[] arr = new int[size];
        for(int i = 0; i < size; ++i){
            arr[i] = stack.pop().val;
        }
        return arr;
    }

next part , 来复习下java Stack类


Java Stack类

  • 栈是Vector的一个子类,它实现了一个标准的后进先出的栈。堆栈只定义了默认构造函数,用来创建一个空栈。 堆栈除了包括由Vector定义的所有方法,也定义了自己的一些方法。
  • boolean empty() :测试堆栈是否为空。
  • Object peek( ):查看堆栈顶部的对象,但不从堆栈中移除它。
  • Object pop( ):移除堆栈顶部的对象,并作为此函数的值返回该对象。
  • Object push(Object element):把项压入堆栈顶部。
  • int search(Object element):返回对象在堆栈中的位置,以 1 为基数。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值