您的位置:首页 > 健康 > 养生 > 【Hot100】LeetCode—160. 相交链表

【Hot100】LeetCode—160. 相交链表

2024/10/6 8:26:10 来源:https://blog.csdn.net/weixin_44382896/article/details/141301907  浏览:    关键词:【Hot100】LeetCode—160. 相交链表

目录

  • 1- 思路
    • 思路
  • 2- 实现
    • ⭐160. 相交链表——题解思路
  • 3- ACM 实现


  • 原题连接:160. 相交链表

1- 思路

思路

  • 首先想要找到相交点,需要定义连个指针。两个指针一定得是同步的,例如 A 链表 [1,2,3,4,5] ,链表 B 是 [4,5]
    • 1- 指针对齐:则需要指针1 先移动,移动长度为 lenA - lenB
    • 2- 同时移动:移动指针1指针2 ,遇到相等则返回相等结点,否则返回 null

2- 实现

⭐160. 相交链表——题解思路

在这里插入图片描述

public class Solution {public ListNode getIntersectionNode(ListNode headA, ListNode headB) {ListNode nodeA = headA;ListNode nodeB = headB;int lenA = 0;int lenB = 0;while(nodeA!=null){lenA++;nodeA = nodeA.next;}while(nodeB!=null){lenB++;nodeB = nodeB.next;}if(lenB>lenA) return getIntersectionNode(headB,headA);nodeA = headA;nodeB = headB;// 1. 先移动第一个指针 for(int i = 0 ; i < lenA-lenB;i++){headA = headA.next;}while(headA!=null || headB!=null){if(headA==headB){return headA;}headA = headA.next;headB = headB.next;}return null;}
}

3- ACM 实现

public class getIntersectionNode {public static class ListNode {int val;ListNode next;ListNode(int x) {val = x;next = null;}}public static ListNode getIntersection(ListNode head1,ListNode head2){ListNode curA = head1;ListNode curB = head2;int len1 = 0;int len2 = 0;while(curA!=null){len1++;curA = curA.next;}while(curB!=null){len2++;curB = curB.next;}if(len1<len2) return getIntersection(head2,head1);// 遍历curA = head1;curB = head2;while (curA!=null || curB !=null){if(curA == curB){return curA;}curA = curA.next;curB = curB.next;}return null;}public static void main(String[] args) {Scanner sc = new Scanner(System.in);// 读取第一个链表的节点数量int n1 = sc.nextInt();ListNode head1 = null, tail1 = null;for (int i = 0; i < n1; i++) {int val = sc.nextInt();ListNode newNode = new ListNode(val);if (head1 == null) {head1 = newNode;tail1 = newNode;} else {tail1.next = newNode;tail1 = newNode;}}// 读取第二个链表的节点数量int n2 = sc.nextInt();ListNode head2 = null, tail2 = null;for (int i = 0; i < n2; i++) {int val = sc.nextInt();ListNode newNode = new ListNode(val);if (head2 == null) {head2 = newNode;tail2 = newNode;} else {tail2.next = newNode;tail2 = newNode;}}// 读取交点位置int intersectionIndex = sc.nextInt();if (intersectionIndex >= 0) {ListNode intersectionNode = head1;for (int i = 0; i < intersectionIndex; i++) {if (intersectionNode != null) {intersectionNode = intersectionNode.next;}}if (tail2 != null) {tail2.next = intersectionNode;}}System.out.println("结果是"+getIntersection(head1,head2).val);}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com