剑指 Offer(easy) 06. 从尾到头打印链表(Java)

原题链接

题目描述

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

示例 

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

解题思路 

  • 常规思路                                                                                                                          逆置该链表,然后再对该链表进行遍历,将元素添加至创建的数组中,返回该数组。(要注意判空)。(头插法逆置)
  • 利用栈的特点                                                                                                                    利用栈先入后出的特点,对该链表进行遍历,对遇到的元素都压入栈,然后创建数组把栈中的元素逐个pop出,所得数组即从尾到头的顺序。

代码 

//逆置链表遍历


class Solution {
    public int[] reversePrint(ListNode head) {
        if(head==null){
            return new int[0];
        }
        int len=0;
        ListNode p=head;
        ListNode cur1=p.next;
        ListNode cur2=cur1;
        while(cur2!=null){
            cur2=cur2.next;
            cur1.next=p;
            p=cur1;
            cur1=cur2;
            len++;
        }
        len+=1;
        int []nums=new int [len];
        int i=0;
        head.next=null;
        while(p!=null){
            nums[i++]=p.val;
            p=p.next;
        }
        return nums;
    }
}


//栈:先入后出
class Solution {
    public int[] reversePrint(ListNode head) {
        Stack<ListNode> stack = new Stack<ListNode>();
        ListNode temp = head;
        while (temp != null) {
            stack.push(temp);
            temp = temp.next;
        }
        int size = stack.size();
        int[] print = new int[size];
        for (int i = 0; i < size; i++) {
            print[i] = stack.pop().val;
        }
        return print;
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值