首页 > 代码库 > 剑指offer---两个链表的第一个公共结点
剑指offer---两个链表的第一个公共结点
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: int Getlength(ListNode* pNode) { int length = 0; ListNode* A = pNode; while (A != NULL) { ++length; A = A->next; } return length; } ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) { int length1 = Getlength( pHead1); int length2 = Getlength( pHead2); int bushu = abs(length1 - length2); ListNode* curNode; ListNode* firstCommonNode; if (length1 >= length2) { curNode = pHead1; while (bushu != 0) { curNode = curNode->next; --bushu; } while ((pHead2 != NULL) && (curNode != NULL) && (curNode != pHead2)) { pHead2 = pHead2->next; curNode = curNode->next; } firstCommonNode = curNode; return firstCommonNode; } else { curNode = pHead2; while (bushu != 0) { curNode = curNode->next; --bushu; } while ((pHead1 != NULL) && (curNode != NULL) && (curNode != pHead1)) { pHead1 = pHead1->next; curNode = curNode->next; } firstCommonNode = curNode; return firstCommonNode; } } };
剑指offer---两个链表的第一个公共结点
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。