找到两链表的第一个公共节点

【题目描述】

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

        For example, the following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

begin to intersect at node c1.

 
【解题思路】
    如果两个链表在某一个节点处汇合,那么其后的部分将成为二者的公共部分。

 

 1 /*
 2 struct ListNode {
 3     int val;
 4     struct ListNode *next;
 5     ListNode(int x) :
 6             val(x), next(NULL) {
 7     }
 8 };*/
 9 class Solution {
10 public:
11     ListNode* FindFirstCommonNode( ListNode *pHead1, ListNode *pHead2) {
12         if(pHead1==NULL||pHead2==NULL)
13             return NULL;
14         int listLen1=0;
15         int listLen2=0;
16         ListNode * pNode1=pHead1;
17         ListNode * pNode2=pHead2;
18         while(pNode1->next!=NULL)
19         {
20             pNode1=pNode1->next;
21             ++listLen1;
22         }
23         while(pNode2->next!=NULL)
24         {
25             pNode2=pNode2->next;
26             ++listLen2;
27         }
28 
29         if(pNode1!=pNode2)
30             return NULL;
31         else
32         {
33         int count=listLen1>listLen2?listLen1-listLen2:listLen2-listLen1;
34         if(listLen1>listLen2)
35         {
36             pNode1=pHead1;
37             pNode2=pHead2;
38         }
39         else
40         {
41             pNode1=pHead2;
42             pNode2=pHead1;
43         }
44 
45         while(count)
46         {
47             pNode1=pNode1->next;
48             --count;
49         }
50 
51         while(pNode1->next!=NULL&&pNode1!=pNode2)
52         {
53             pNode1=pNode1->next;
54             pNode2=pNode2->next;
55         }
56         return pNode1;
57         }    
58     }
59 };

 


Notes:

  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
  • Your code should preferably run in O(n) time and use only O(1) memory.
【代码实现】
 

转载于:https://www.cnblogs.com/lou424/p/5038103.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值