求相交链表,两个指针的爱情

若两人有缘,终会相遇

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if(headA==NULL||headB==NULL)
            return NULL;
        ListNode* you=headA;
        ListNode* she=headB;
        while(you!=she)//若是有缘,两人终会相遇
        {
            if(you==NULL)
                you=headB;//当你走到终点时,开始走她走过的路
            else
                you=you->next;
            if(she==NULL)
            {
                she=headA;// 当她走到终点时,开始走你走过的路
            }   
            else
                she=she->next;
        }
        /*
        while(she)//两人若是喜欢彼此
        {
        	//那么一路上
        	you=she->next;//你踩着她的影子
        	she=you->next;//她踩着你的影子
        	//携手度过生命中剩下的旅途
        }*/
        return node1;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你好,下面是用C++创建两个相交链表的示例代码: ```c++ #include <iostream> using namespace std; // 定义链表节点 struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; // 创建两个相交链表 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode *p1 = headA, *p2 = headB; while (p1 != p2) { // 遍历到链表末尾后,从另外一个链表头部继续遍历 p1 = p1 == nullptr ? headB : p1->next; p2 = p2 == nullptr ? headA : p2->next; } return p1; } int main() { // 创建第一个链表 ListNode *headA = new ListNode(1); ListNode *n1 = new ListNode(2); ListNode *n2 = new ListNode(3); ListNode *n3 = new ListNode(4); headA->next = n1; n1->next = n2; n2->next = n3; // 创建第二个链表 ListNode *headB = new ListNode(5); ListNode *m1 = new ListNode(6); ListNode *m2 = new ListNode(7); ListNode *m3 = n2; // 第二个链表从第一个链表的第三个节点开始相交 headB->next = m1; m1->next = m2; m2->next = m3; // 遍历两个链表验证相交 ListNode *intersectionNode = getIntersectionNode(headA, headB); if (intersectionNode != nullptr) { cout << "链表相交点为:" << intersectionNode->val << endl; } else { cout << "链表相交" << endl; } return 0; } ``` 输出结果: ``` 链表相交点为:3 ``` 在这个例子中,我们创建了两个相交链表,然后通过 `getIntersectionNode` 函数遍历两个链表,找到它们的相交点,并返回相交点的指针。在主函数中,我们输出了相交点的值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值