【LeetCode】从尾到头打印链表&&反转链表&&复杂链表的复制

3.从尾到头打印链表

题目:

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

题解:
  • 遍历节点,将数据压栈
  • 弹栈,数据存储在数组中
public int[] reversePrint(ListNode head) {
        int index = 0;
        if (head == null){
            return new int[0];
        }
        Stack stack = new Stack<Integer>();
        while (head != null){
            stack.push(head.val);
            head = head.next;
        }
        int[] res = new int[stack.size()];
        while (!stack.empty()){
            res[index] = (int)stack.pop();
            index++;
        }
        return res;
    }

4.反转链表

题目:

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

题解:

使用栈结构进行反转

注意:

在对栈内弹出的节点ListNode进行重新装配形成list的过程中,注意将ListNode.next置为null,否则会出现环

    public ListNode reverseList(ListNode head) {
        Stack<ListNode> stack = new Stack<>();
        while (head != null){
            stack.push(head);
            head = head.next;
        }
        ListNode temp = new ListNode(0);
        ListNode res = temp;
        while (!stack.empty()){
            ListNode ln = stack.pop();
            //注意:将弹出的ListNode的next置为空,否则会形成闭环
            ln.next = null;
            temp.next = ln;
            temp = temp.next;
        }
        return res.next;
    }

5.复杂链表的复制

题目:

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

题解:

考察深拷贝,难点在于比如创建新节点1,而旧节点的random节点为5,此时新的链表中并不存在节点5,就会造成指针指向原节点的错误。

  • 使用map将原node与新node进行一一对应

  • 第一次遍历得到新旧节点的对应关系

  • 旧节点的next节点对应的新节点赋值给新节点的next

    • newNode.next = map(OldNode.next)

    • map.get(cur).next = map.get(cur.next);

  • random节点以此类推

    public Node copyRandomList(Node head) {

        HashMap<Node, Node> map = new HashMap<>();
        Node cur = head;
        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、付费专栏及课程。

余额充值