【剑指offer第二天】链表

这篇博客探讨了两种不同的链表操作方法。首先,介绍了如何使用栈实现从尾到头打印链表,通过将节点值压入栈中,然后依次弹出得到逆序的打印结果。接着,展示了如何递归地反转链表。最后,讲解了深度复制链表的策略,通过遍历链表并在哈希表中存储节点值,然后根据原链表为新链表分配next和random指针,实现链表的完整复制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目一 从尾到头打印链表

在这里插入图片描述

方法一 利用栈

借助栈存储,再从栈中弹出存到数组中

class Solution {
    public int[] reversePrint(ListNode head) {
        Deque<Integer> tmp = new LinkedList<>();
        while(head!=null){
            tmp.push(head.val);
            head = head.next;
        }
        int l = tmp.size();
        int []res = new int[l];
        for(int i = 0;i < l;i++){
            res[i] = tmp.pop();
        }
        return res;
    }
}

方法二 递归

class Solution {
    ArrayList<Integer> tmp = new ArrayList<>();
    public int[] reversePrint(ListNode head) {
        recur(head);
        int l = tmp.size();
        int []res = new int[l];
        for(int i = 0;i < l;i++){
            res[i] = tmp.get(i);
        }
        return res;
    }
    void recur(ListNode head){
        if(head == null) return;
        recur(head.next);
        tmp.add(head.val);
    }
}

题目二 反转链表

在这里插入图片描述

题目三

在这里插入图片描述
深度复制,首先遍历链表在哈希表中存储结点的值,之后再次遍历链表,对新建的结点的next和random进行赋值

class Solution {
    public Node copyRandomList(Node head) {
        if(head == null) return null;
        Node cur = head;
        Map<Node,Node> map = new HashMap<>();
        while(cur != null){
            map.put(cur,new Node(cur.val));
            cur = cur.next;
        }
        cur = head;
        while(cur != null){
            map.get(cur).next = map.get(cur.next);
            map.get(cur).random = map.get(cur.random);
            cur = cur.next;
        }
        return map.get(head);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值