两个链表是否相交节点

题目

给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。

两个链表相交节点https://leetcode-cn.com/problems/intersection-of-two-linked-lists/

代码


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }

 * 可以理解成两个人速度一致, 走过的路程一致。那么肯定会同一个时间点到达终点。
 * 走到尽头见不到你,于是走过你来时的路,等到相遇时才发现,你也走过我来时的路。
 * 给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
                //边界限制
        if (headA == null || headB == null) {
            return null;
        }
        ListNode preA=headA,preB=headB;
        while (preA!= preB) {
            preA = preA == null ? headB : preA.next;
            preB = preB == null ? headA : preB.next;
        }
        return preA;
    }
}

复杂链表的复制icon-default.png?t=M0H8https://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;
    }
}
*/
class Solution {
    public Node copyRandomList(Node head) {
        //边界限制
        if (head == null) {
            return null;
        }
        //声明一个hashSet 存储新老节点对应关系
        Map<Node, Node> map = new HashMap<>();
        Node node = head;
        while (node != null) {
            //k 原始节点 v 新节点数值,无指向
            map.put(node, new Node(node.val));
            node = node.next;
        }

        //整理新节点指向问题
        node = head;
        while (node != null) {
            map.get(node).next=map.get(node.next);
            map.get(node).random=map.get(node.random);
            node = node.next;
        }
        return map.get(head);

    }
}

反转单向链表icon-default.png?t=M0H8https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/submissions/

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        //时间复杂度为 O(N)  间复杂度为 O(1)
        ListNode cur = head, pre = null;
        //边界限制
        if (head == null) {
            return null;
        }
        while (cur != null) {

            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;

        }
        return pre;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值