public ListNode GetIntersectionNode(ListNode headA, ListNode headB) { var pointA = headA; var pointB = headB; if(headA != null && headB != null) { while(pointA != pointB) { if(pointA == null) { pointA = headB; } else { pointA = pointA.next; } if(pointB == null) { pointB = headA; } else { pointB = pointB.next; } if((pointA == null) && (pointB == null)) { return null; } } return pointA; } else { return null; } } 或者 等同于 if (headA == null || headB == null) return null; ListNode currA = headA; ListNode currB = headB; while (currA!=currB) { currA = currA == null ? headB : currA.next; currB = currB == null ? headA : currB.next; } return currA;
private static ListNode GetIntersectionNode2(ListNode headA, ListNode headB) { var nodeA = headA; var nodeB = headB; var set = new HashSet<ListNode>(); while(nodeA != null) { set.Add(nodeA); nodeA = nodeA.next; } while(nodeB != null) { if(set.Contains(nodeB)) { return nodeB; } nodeB = nodeB.next; } return null; }