1 题目:
两个链表的第一个公共结点_牛客题霸_牛客网 (nowcoder.com)
2 参考;
解题;代码随想录 (programmercarl.com) 面试题 02.07. 链表相交 - 力扣(LeetCode)
3 代码:
注意相同的是地址指针,而不是val
C++
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* curA = headA;
ListNode* curB = headB;
int lenA = 0, lenB = 0;
while (curA != NULL) { // 求链表A的长度
lenA++;
curA = curA->next;
}
while (curB != NULL) { // 求链表B的长度
lenB++;
curB = curB->next;
}
curA = headA;
curB = headB;
// 让curA为最长链表的头,lenA为其长度
if (lenB > lenA) {
swap (lenA, lenB);
swap (curA, curB);
}
// 求长度差
int gap = lenA - lenB;
// 让curA和curB在同一起点上(末尾位置对齐)
while (gap--) {
curA = curA->next;
}
// 遍历curA 和 curB,遇到相同则直接返回
while (curA != NULL) {
if (curA == curB) {
return curA;
}
curA = curA->next;
curB = curB->next;
}
return NULL;
}
};
Python3
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# @param pHead1 ListNode类
# @param pHead2 ListNode类
# @return ListNode类
#
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
cur1 = pHead1
l1 = 0
while cur1:
cur1 = cur1.next
l1 += 1
cur2 = pHead2
l2 = 0
while cur2:
cur2 = cur2.next
l2 += 1
l = abs(l1-l2)
if l1 >= l2:
while l:
pHead1 = pHead1.next
l -= 1
else:
while l:
pHead2 = pHead2.next
l -= 1
while pHead1:
if pHead1 == pHead2:
return pHead1
else:
pHead1 = pHead1.next
pHead2 = pHead2.next
return None