题意:
解题思路:
思路:
* [Hash]
* 同时移动两个链表,链表到达尾部,则指向另外一个链表头部,继续遍历,这样会抵消长度差;
* 如果没有相交,则代表长度相等,最后会是 nil == nil,反之有相交;
PHP代码实现:
/**
* Definition for a singly-linked list.
* class ListNode {
* public $val = 0;
* public $next = null;
* function __construct($val) { $this->val = $val; }
* }
*/
class Solution {
/**
* @param ListNode $headA
* @param ListNode $headB
* @return ListNode
*/
function getIntersectionNode($headA, $headB) {
if ($headA === null || $headB === null) {
return null;
}
$curA = $headA;
$curB = $headB;
while ($curA !== $curB) {
$curA = ($curA === null) ? $headB : $curA->next;
$curB = ($curB === null) ? $headA : $curB->next;
}
return $curA;
}
function getIntersectionNodeHash($headA, $headB) {
$curA = $headA;
$curB = $headB;
$map = [];
while ($curA != null) {
array_push($map, $curA);
$curA = $curA->next;
}
while ($curB != null) {
if (in_array($curB, $map, true)) {
return $curB;
}
$curB = $curB->next;
}
return null;
}
}
GO代码实现:
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func getIntersectionNode(headA, headB *ListNode) *ListNode {
curA,curB := headA,headB
for curA != curB {
if curA == nil {
curA = headB
} else {
curA = curA.Next
}
if curB == nil {
curB = headA
} else {
curB = curB.Next
}
}
return curA
}