输入两个无环的单向链表,找出它们的第一个公共结点,如果没有公共节点则返回空。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
数据范围:
要求:空间复杂度
,时间复杂度 ![](https://www.nowcoder.com/equation?tex=O(n))
要求:空间复杂度
例如,输入{1,2,3},{4,5},{6,7}时,两个无环的单向链表的结构如下图所示:
可以看到它们的第一个公共结点的结点值为6,所以返回结点值为6的结点。
输入分为是3段,第一段是第一个链表的非公共部分,第二段是第二个链表的非公共部分,第三段是第一个链表和第二个链表的公共部分。 后台会将这3个参数组装为两个链表,并将这两个链表对应的头节点传入到函数FindFirstCommonNode里面,用户得到的输入只有pHead1和pHead2。
返回传入的pHead1和pHead2的第一个公共结点,后台会打印以该节点为头节点的链表。
{1,2,3},{4,5},{6,7}
{6,7}
第一个参数{1,2,3}代表是第一个链表非公共部分,第二个参数{4,5}代表是第二个链表非公共部分,最后的{6,7}表示的是2个链表的公共部分 这3个参数最后在后台会组装成为2个两个无环的单链表,且是有公共节点的
{1},{2,3},{}
{}
2个链表没有公共节点 ,返回null,后台打印{}
/*function ListNode(x){ this.val = x; this.next = null; }*/ function FindFirstCommonNode(pHead1, pHead2) { // write code here while(pHead1) { pHead1.visited = true pHead1 = pHead1.next } while(pHead2) { if(pHead2.visited) { return pHead2 } pHead2 = pHead2.next } return null } module.exports = { FindFirstCommonNode : FindFirstCommonNode };
function FindFirstCommonNode(pHead1, pHead2) { // write code here if (pHead1 == null || pHead2 == null) { return null; } let p1 = pHead1; let p2 = pHead2; while (p1 != p2) { p1 = p1.next == null ? pHead2 : p1.next; p2 = p2.next == null ? pHead1 : p2.next; } return p1; }
function FindFirstCommonNode(pHead1, pHead2) { // write code here if(pHead1 === null || pHead2 === null) return null; const fast = pHead2; while(pHead1){ while(pHead2){ if(pHead1 === pHead2) return pHead1; pHead2 = pHead2.next; } pHead1 = pHead1.next; pHead2 = fast; } }快慢指针
/*function ListNode(x){ this.val = x; this.next = null; }*/ function FindFirstCommonNode(pHead1, pHead2) { // write code here let p1 = pHead1 let p2 = pHead2 if (p1 == null || p2 == null) { return null } while (true) { p1.flag = true if (p1.next == null) { break } p1 = p1.next } while (true) { if (p2.flag === true) { return p2 } if (p2.next == null) { break } p2 = p2.next } return null } module.exports = { FindFirstCommonNode: FindFirstCommonNode };暴力解法
function FindFirstCommonNode(pHead1, pHead2) { // write code here if (pHead1 == null || pHead2 == null) return null; let p1 = pHead1; let p2 = pHead2; while (p1 !== p2){ p1 = p1.next; p2 = p2.next; if (p1 === p2) break; if (p1 === null) p1 = pHead2; if (p2 === null) p2 = pHead1; } return p1; }