目的:找到两个链表的相交节点并且返回该节点。
示例:在节点c1处相交
算法思想:因为两个链表的总长度一定,所以遍历A+B链表,如果A、B两节点相交,则末尾节点一定相同。
遍历两个单链表,若A链表第一次遍历完后,将该末尾节点指向B链表的头节点,同理,B链表遍历完后,将末尾节点指向A链表的头节点,
如果遍历途中两个链表在某个节点相遇,这个节点即为相交节点,如果两个链表遍历完后没有相遇,则两个链表没有相交。
public class SelectedInterNode { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { ListNode resA = headA; ListNode resB = headB; ListNode res = new ListNode(0); ListNode selectnode = res; if(resA == null || resB == null){ return null; } while(resA != resB){ resA = resA.next; resB = resB.next; if(resA == null && resB == null){ return null; } if(resA == null){ resA = headB; } if(resB == null){ resB = headA; } } selectnode = resA; return selectnode; } }