2022.4.19 剑指offer 06,24,35

学习剑指offer 第二天

06 从尾到头打印链表

  • 解析
    法一:建一个长度为size的数组,也就分为两步:找出数组长度+构造新数组
public int[] reversePrint(ListNode head) {
        //首先建立一个长度的size的数组,第一步就要获取链表长度
        int size = 0;
        ListNode temp = head;
        while(head != null){
            size++;
            head = head.next;
        }
        int[] result = new int[size];
        while(temp != null){
            result[--size] = temp.val;
            temp = temp.next;
        }
        return result;
    }

法二:使用栈的后入先出原理

public int[] reversePrint(ListNode head) {
        //使用栈的后入先出原理
        Deque<Integer> stack = new LinkedList<>();
        while(head != null){
            stack.push(head.val);
            head = head.next;
        }
        int[] result = new int[ stack.size()];
        int index = 0;
        while(!stack.isEmpty()){
            result[index++] = stack.pop();
        }
        return result;
    }

24 反转链表

  • 解析
    只需要反转指针即可
class Solution {
    public int[] reversePrint(ListNode head) {
        //使用栈的后入先出原理
        Deque<Integer> stack = new LinkedList<>();
        while(head != null){
            stack.push(head.val);
            head = head.next;
        }
        int[] result = new int[ stack.size()];
        int index = 0;
        while(!stack.isEmpty()){
            result[index++] = stack.pop();
        }
        return result;
    }
}
35 复杂链表的复制
  • 题目描述
    请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
  • 解析
    使用哈希表+递归
    哈希表用来存储旧节点-新节点的映射
    使用递归不断创建没有遍历到的节点
class Solution {
    //原节点 -> 新节点
    Map<Node, Node> mymap = new HashMap<>();
    public Node copyRandomList(Node head) {
        if(head == null) return null;
       Node new_head = new Node(head.val);
        mymap.put(head, new_head);
       if(head.next != null){
           if(mymap.containsKey(head.next)){
               new_head.next = mymap.get(head.next);
           }else{
               Node new_next = copyRandomList(head.next);
               new_head.next = new_next;
           }      
       }

       if(head.random != null){
           if(mymap.containsKey(head.random)){
               new_head.random = mymap.get(head.random);
           }else{
               Node new_random = copyRandomList(head.random);
               new_head.random = new_random;
           }      
       }

       return new_head;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值