【链表】两个链表的第一个公共结点

本文介绍了一种算法,用于查找两个链表的第一个公共结点。通过计算两个链表的长度差并调整遍历起点,确保同时到达公共部分,从而找到第一个公共节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

输入两个链表,找出它们的第一个公共结点。

 

 1 public class Solution {
 2     
 3     /**
 4      * 思路:两个链表相交,存在公共的链表尾,根据链表长度的差值,移动指针,找到第一个相同的节点,即为第一个公共节点
 5      * @param pHead1
 6      * @param pHead2
 7      * @return
 8      */
 9     public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
10 
11         if (pHead1 == null || pHead2 == null) {
12             return null;
13         }
14 
15         int d = 0;
16 
17         ListNode p1 = pHead1;
18         ListNode p2 = pHead2;
19 
20         int length1 = 0;
21         while (pHead1 != null) {
22             length1++;
23             pHead1 = pHead1.next;
24         }
25 
26         int length2 = 0;
27         while (pHead2 != null) {
28             length2++;
29             pHead2 = pHead2.next;
30         }
31 
32         if (length1 > length2) {
33             d = length1 - length2;
34 
35             while (d > 0) {
36                 p1 = p1.next;
37                 d--;
38             }
39         } else if (length1 < length2) {
40             d = length2 - length1;
41 
42             while (d > 0) {
43                 p2 = p2.next;
44                 d--;
45             }
46         } else {
47             return p1;
48         }
49 
50         while (p1 != null) {
51             if (p1 == p2) {
52                 break;
53             }
54             p1 = p1.next;
55             p2 = p2.next;
56         }
57         return p1;
58     }
59 }
60 
61 class ListNode {
62     int val;
63     ListNode next = null;
64 
65     ListNode(int val) {
66         this.val = val;
67     }
68 }

 

转载于:https://www.cnblogs.com/jiangyi-uestc/p/5840808.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值