题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
http://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
/**
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
struct ListNode* FindFirstCommonNode(struct ListNode* pHead1, struct ListNode* pHead2 ) {
// write code here
struct ListNode *p1 = pHead1,*p2;
while(p1 != NULL)
{
p1->val = -p1->val;
p1 = p1->next;
}
p1 = pHead2;
while(p1 != NULL)
{
if(p1->val<0) break;
p1 = p1->next;
}
if(p1 == NULL) return NULL;
p2 = p1;
while(p1 != NULL)
{
p1->val = -p1->val;
p1 = p1->next;
}
return p2;
}
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
/**
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
struct ListNode* FindFirstCommonNode(struct ListNode* pHead1, struct ListNode* pHead2 ) {
// write code here
struct ListNode *p1 = pHead1,*p2;
while(p1 != NULL)
{
p1->val = -p1->val;
p1 = p1->next;
}
p1 = pHead2;
while(p1 != NULL)
{
if(p1->val<0) break;
p1 = p1->next;
}
if(p1 == NULL) return NULL;
p2 = p1;
while(p1 != NULL)
{
p1->val = -p1->val;
p1 = p1->next;
}
return p2;
}