题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
struct ListNode* FindFirstCommonNode(struct ListNode* pHead1,
struct ListNode* pHead2 ) {
// write code here
struct ListNode *node1 = pHead1;
struct ListNode *node2 = pHead2;
struct ListNode *head = NULL;
if (!node1 || !node2)
return NULL;
while(node1) {
node1->val |= 1 << 20;
node1 = node1->next;
}
while(node2) {
if ((node2->val >> 20) & 0x1) {
if (!head)
head = node2;
node2->val &= ~(1 << 20);
}
node2 = node2->next;
}
node1 = pHead1;
while(node1) {
node1->val &= ~(1 << 20);
node1 = node1->next;
}
return head;
}
查看8道真题和解析
海康威视公司福利 1409人发布