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

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
//这是一个比较简单的题,首先,我们可以知道,单项链表要是有一个公共结点,则这两个链表的形式可以表示为一个‘Y’
//一开始的时候,我并没有考虑到两个链表的长度不同问题
//看了解析以及书上的思路,写出下面的代码
//链表的遍历还是比较简单的
//只不过就我自己而言,之前由于写了多项式的相乘相加时,中间出了一些问题导致现在对于链表遍历时要用当前这个节点还是要保存其后那个节点,有些晕晕的
//看来还是要多练习
class Solution {
public:
    int GetLenofList(ListNode* pHead)
    {
        if(pHead==NULL)
            return 0;
        ListNode* tmp=pHead;
        int count;
        while(tmp!=NULL){
            count++;
            tmp = tmp->next;
        }
        return count;
            
    }
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        //得到两个链表的长度
        int len1=GetLenofList(pHead1);
        int len2=GetLenofList(pHead2);
        ListNode* firstCommonNode = NULL;
        int diff = len1-len2;
        ListNode* tmplong = pHead1;
        ListNode* tmpshort = pHead2;
        if(len2>len1){
            diff = len2-len1;
            tmplong = pHead2;
            tmpshort = pHead1;
        }
       
        //长的链表多走几步
        for(int i = 0; i<diff; i++)
            tmplong = tmplong->next;
        while(tmplong!=NULL&&tmpshort!=NULL){
            if(tmplong==tmpshort){
                firstCommonNode = tmplong;
                break;
            }
            tmplong= tmplong->next;
            tmpshort=tmpshort->next;
        }
        return firstCommonNode;    


    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值