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

题目描述

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

代码

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        int len1 = len(pHead1), len2 = len(pHead2);
        ListNode *cur1 = pHead1, *cur2 = pHead2;
        int dif = len1 - len2;
        
        if (len1 < len2) {//cur1指向长的
            cur1 = pHead2, cur2 = pHead2;
            dif = len2 - len1;
        }
        
        int count = 0;
        while (count < dif) {
            cur1 = cur1->next;
            ++count;
        }
        
        while (cur2 != NULL) {
            if (cur1 == cur2) {
                return cur1;
            }
            cur1 = cur1->next;
            cur2 = cur2->next;
        }
        return NULL;
    }
    
    int len(ListNode* head) {//邱链表长度
        ListNode* cur = head;
        int count = 0;
        while (cur != NULL) {
            ++count;
            cur = cur->next;
        }
        return count;
    }
};

posted on 2017-03-20 17:13  jec  阅读(92)  评论(0编辑  收藏  举报

导航