两个链表的第一个公共结点(c++&&go)

/* 输入两个无环的单向链表,找出它们的第一个公共结点,如果没有公共节点则返回空。
(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
 */
#include <bits/stdc++.h>

struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};

class Solution {
public:
    // 1.链长先走。
    // 2.走到剩余断链的长度,同步遍历找共同结点

    int getCount(ListNode *pHead)
    {
        int count = 0;
        while (pHead)
        {
            count++;
            pHead = pHead->next;
        }
        return count;
    }

    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) 
    {
        if (!pHead1 || !pHead2)
        {
            return nullptr;
        }
        
        int listCnt1 = getCount(pHead1);
        int listCnt2 = getCount(pHead2);
        int step = listCnt1 - listCnt2;
        if (step > 0)
        {
            while (step)
            {
                pHead1 = pHead1->next;
                step--;
            }
        }
        else
        {
            int nStep = abs(step);
            while (nStep)
            {
                pHead2 = pHead2->next;
                nStep--;
            }
        }

        while(pHead1 && pHead2)
        {
            if(pHead1 == pHead2)
            {
                return pHead1;
            }
            else
            {
                pHead1 = pHead1->next;
                pHead2 = pHead2->next;
            }
        }

        return nullptr;
    }
};

int main()
{
    ListNode* pHead1 = new ListNode(1);
    pHead1->next = new ListNode(2);
    pHead1->next->next = new ListNode(3);

    ListNode* pHead2 = new ListNode(2);
    pHead2->next = new ListNode(3);

    Solution cSolution;
    cSolution.FindFirstCommonNode(pHead1, pHead2);
    return 1;
}
/* 输入两个无环的单向链表,找出它们的第一个公共结点,如果没有公共节点则返回空。
(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
*/

package main

import "math"

type ListNode struct {
	Val  int
	Next *ListNode
}

/**
 *
 * @param pHead1 ListNode类
 * @param pHead2 ListNode类
 * @return ListNode类
 */

func getCount(pHead *ListNode) int {
	nCnt := 0
	for pHead != nil {
		nCnt++
		pHead = pHead.Next
	}
	return nCnt
}

func FindFirstCommonNode(pHead1 *ListNode, pHead2 *ListNode) *ListNode {
	if pHead1 == nil || pHead2 == nil {
		return nil
	}

	list1 := getCount(pHead1)
	list2 := getCount(pHead2)
	step := list1 - list2
	if step > 0 {
		for step > 0 {
			step--
			pHead1 = pHead1.Next
		}
	} else {
		nStep := math.Abs(float64(step))
		for nStep > 0 {
			nStep--
			pHead2 = pHead2.Next
		}
	}

	for pHead1 != nil && pHead2 != nil {
		if pHead1 == pHead2 {
			return pHead1
		} else {
			pHead1 = pHead1.Next
			pHead2 = pHead2.Next
		}
	}
	return nil
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值