0
点赞
收藏
分享

微信扫一扫

算法训练——剑指offer(链表问题)

小布_cvg 2022-01-30 阅读 65
算法

摘要

本系列博文将主要是学习和分享的算法基本相关问题和解答思路,帮助小伙伴更好理解相关的算法中有关于链表的内容。

一、链表原理与解题方法

二、链表相关算法练习题目

从尾到头打印链表_牛客题霸_牛客网

解题思路:

//一种是将数据放入栈中 ,然后在取出
    public ArrayList<Integer> printListFromTailToHead1(ListNode listNode) {
        ArrayList<Integer> res = new ArrayList<Integer>();
        Stack<Integer> stack = new Stack<Integer>();
        while (listNode != null) {
            stack.add(listNode.val);
            listNode = listNode.next;
        }
        while (stack.size() != 0) {
            res.add(stack.pop());
        }
        return res;
    }

  //将链表翻转(方法一) 然后在读取链表的数据
    public ArrayList<Integer> printListFromTailToHead2(ListNode listNode) {
        ArrayList<Integer> res = new ArrayList<Integer>();
        //初始化pre=null curr=listnode
        ListNode pre = null;
        ListNode curr = listNode;
        while (curr != null) {
            ListNode temp=curr.next;
            curr.next=pre;//翻转指针
            pre=curr;//前指后
            curr=temp;//前指后
        }
        while (pre!=null){
            res.add(pre.val);
            pre=pre.next;
        }
        return res;
    }

博文参考

举报

相关推荐

0 条评论