leetcode练题:剑指offer

6 篇文章 0 订阅

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

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        // 利用栈后进先出的特性,先将元素入栈,
        // 再将元素出栈,放入数组中
        // 返回数组
        Stack<ListNode> stack = new Stack<ListNode>();
        // 定义变量,变量和head相同
        ListNode tmp = head;
        // 将所有的元素入栈
        while(tmp != null){
            stack.push(tmp);
            tmp = tmp.next;
        }
        // 将元素出栈,并且存入到数组中
        int sz = stack.size();
        int[] a = new int[sz];
        for(int i = 0;i < sz;i++){
            a[i] = stack.pop().val;
        }
        return a;
    }
}

二、定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        // 设置两个指针,一个表示当前指针,一个是头指针
        ListNode pCur = head;
        ListNode pPrev = null;
        while(pCur != null){
            // 定义一个指针存储当前指针的下一个指针
            ListNode next = pCur.next;
            pCur.next = pPrev;
            pPrev = pCur;
            pCur = next;
        }
        return pPrev;
    }
}

三、

请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

/*
// Definition for a Node.
class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}
*/

// 递归的方式获取每一个节点的next和random
// 使用map存储键值对
class Solution {
    // 创建Map存放键值对
    Map<Node,Node> cur = new HashMap<Node,Node>();
    public Node copyRandomList(Node head) {
       if(null == head){
           return null;
       } 
    //    若没有创建节点,则创建节点,containsKey判断对应节点有没有存在
        if(!cur.containsKey(head)){
            // 获取当前节点的值
            Node va = new Node(head.val);
            // 将其存入哈希表中
            cur.put(head,va);
            // head节点的下一个节点为键值对中的键
            va.next = copyRandomList(head.next);
            va.random = copyRandomList(head.random);
        }
        return cur.get(head);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xuruhua

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值