# C#LeetCode刷题之#160-相交链表（Intersection of Two Linked Lists）

A:          a1 → a2
↘
c1 → c2 → c3
↗
B:     b1 → b2 → b3

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

A:          a1 → a2
↘
c1 → c2 → c3
↗
B:     b1 → b2 → b3
begin to intersect at node c1.

Notes:

If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.

```public class Program {

public static void Main(string[] args) {
var headA = new ListNode(1) {
next = new ListNode(2) {
next = new ListNode(1) {
next = new ListNode(2) {
next = new ListNode(3)
}
}
}
};

var headB = new ListNode(1) {
next = new ListNode(2) {
next = new ListNode(3) {
}
}
};

ShowArray(res);

ShowArray(res);

ShowArray(res);

}

private static void ShowArray(ListNode list) {
var node = list;
while(node != null) {
Console.Write(\$"{node.val} ");
node = node.next;
}
Console.WriteLine();
}

//LeetCode超时未AC
while(nodeA != null) {
while(nodeB != null) {
if(nodeA == nodeB) {
return nodeA;
}
nodeB = nodeB.next;
}
nodeA = nodeA.next;
}
return null;
}

var set = new HashSet<ListNode>();
while(nodeA != null) {
nodeA = nodeA.next;
}
while(nodeB != null) {
if(set.Contains(nodeB)) {
return nodeB;
}
nodeB = nodeB.next;
}
return null;
}

while(pointA != pointB) {
if(pointA == null) {
} else {
pointA = pointA.next;
}
if(pointB == null) {
} else {
pointB = pointB.next;
}
if((pointA == null) && (pointB == null)) {
return null;
}
}
return pointA;
} else {
return null;
}
}

public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) { val = x; }
}

}```

```1 2 3
1 2 3
1 2 3```

(2)