二个链表的第一个公共节点

题目描述

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

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        ListNode *p = pHead1;
        ListNode *q = pHead2;
        int len1=0,len2 = 0;
        while(p)
        {
            len1++;
            p = p->next;
        }
        while(q)
        {
            len2++;
            q = q->next;
        }  //find the lenth of List
        
        ListNode *newHead = len1>len2 ? pHead1:pHead2;
        ListNode *head = len1>len2 ? pHead2:pHead1;
        int step = abs(len1-len2);
        while(step > 0)
        {
            newHead = newHead->next;
            step--;
        } //the longer list firsly goes several steps
        
        while(head&&newHead)
        {
            if(head == newHead)
                return head;
            else
            {
                head = head->next;
                newHead= newHead->next;
            }
        }
        return NULL;
        
    }
};

 

### 找到两个链表第一个公共节点 要找到两个链表第一个公共节点,可以采用一种高效的方法来解决这个问题。具体来说,可以通过比较两条链表的长度差异并调整起始位置的方式完成。 以下是具体的解决方案: #### 方法描述 1. **获取链表长度** 首先分别遍历两个链表 `L1` 和 `L2` 来获得其各自的长度 `len1` 和 `len2`[^3]。 2. **计算长度差值** 计算两者之间的长度差值 `dis = |len1 - len2|`。这一步是为了让较长的那个链表先行移动一定的步数,从而使得后续两者的剩余部分具有相同的长度[^4]。 3. **同步前进直到相遇** 调整之后,使两个指针同时向前移动,每次各前进一步。一旦发现当前所指向的内容相同,则找到了首个共同拥有的节点;如果到达结尾仍未遇到一致情况,则表明不存在任何交叉点[^5]。 下面是基于上述逻辑编写的C++代码实现: ```cpp struct ListNode { int val; struct ListNode *next; }; ListNode* findFirstCommonNode(ListNode* headA, ListNode* headB){ if(!headA || !headB) return nullptr; // Step 1: Calculate lengths of both lists. int lengthA = 0, lengthB = 0; ListNode* tempA = headA; ListNode* tempB = headB; while(tempA != NULL){ ++lengthA; tempA = tempA->next; } while(tempB != NULL){ ++lengthB; tempB = tempB->next; } // Reset pointers to start nodes after calculating their respective lengths. tempA = headA; tempB = headB; // Step 2: Move the pointer on longer list forward by difference in lengths. if(lengthA > lengthB){ for(int i=0;i<lengthA-lengthB;++i){ tempA = tempA->next; } }else{ for(int j=0;j<lengthB-lengthA;++j){ tempB = tempB->next; } } // Step 3: Traverse together until they meet or reach end. while(tempA && tempB){ if(tempA == tempB){ return tempA; // Found first common node. } tempA = tempA->next; tempB = tempB->next; } return nullptr; // No intersection found. } ``` 这段程序实现了寻找两个链表第一个公共节点的功能,并且时间复杂度为O(m+n),其中m,n分别是两个输入列表的大小。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值