剑指 Offer 52. 两个链表的第一个公共节点
输入两个链表,找出它们的第一个公共节点。
思想:双指针法,浪漫相遇
public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {ListNode pointA = headA;ListNode pointB = headB;while(pointA!=pointB){pointA =( pointA!=null? pointA.next:headB);pointB =( pointB!=null? pointB.next:headA);}return pointA;}
正确的测试用例:
public static void main(String[] args) {/*** 输入:* 第一行为链表A的所有元素4 1 8 4 5* 第二行为链表B的所有元素5 0 1 8 4 5* 输出:* Reference of the node with value = 8*/ListNode headA = new ListNode(0,null);ListNode pre = headA;System.out.println("Enter a space separated list of numbers:listA = ");Scanner sc = new Scanner(System.in);String line1 = sc.nextLine();System.out.println("Enter a space separated list of numbers:listB =");String line2 = sc.nextLine();System.out.println("skipA = ");int skipA = sc.nextInt();System.out.println("skipB = ");int skipB = sc.nextInt();Scanner sc1 = new Scanner(line1);Scanner sc2 = new Scanner(line2);while (sc1.hasNextInt()){ListNode curr = new ListNode(sc1.nextInt(), null);pre.next = curr;pre = curr;}headA = headA.next;//将首结点下移一个代表真正的首结点System.out.println(headA.toString());ListNode headB = new ListNode(0,null);pre = headB;while (sc2.hasNextInt()){ListNode curr = new ListNode(sc2.nextInt(), null);pre.next = curr;pre = curr;}headB = headB.next;//将首结点下移一个代表真正的首结点ListNode nodeA = headA;ListNode nodeB = headB;//根据skipA和skipB让listA和listB在该相交的结点相交for (int a = skipA; a > 0; a--) {nodeA = nodeA.next;}for (int b = skipB-1; b > 0; b--) {nodeB = nodeB.next;}nodeB.next = nodeA;System.out.println(headB.toString());System.out.println("Reference of the node with value = "+getIntersectionNode(headA, headB).val);}
这里主要是想记录测试代码中遇到的一些bug,按以下的方法测试会永远得出null的结果,因为headA引用和headB引用永远没有交点,即使结点值相同,但他们实际所指的地址并不相同。
还有在设计链表的时候也不要初始为null,null在内存中并没有分配实际的内存地址,会报空指针异常。
错误的测试代码及结果:
public static void main(String[] args) {/*** 输入:* 第一行为链表A的所有元素4 1 8 4 5* 第二行为链表B的所有元素5 0 1 8 4 5* 输出:* Reference of the node with value = 8*/ListNode headA = new ListNode(0,null);ListNode pre = headA;System.out.println("Enter a space separated list of numbers:");Scanner sc = new Scanner(System.in);String line1 = sc.nextLine();System.out.println("Enter a space separated list of numbers:");String line2 = sc.nextLine();Scanner sc1 = new Scanner(line1);Scanner sc2 = new Scanner(line2);while (sc1.hasNextInt()){ListNode curr = new ListNode(sc1.nextInt(), null);pre.next = curr;pre = curr;}headA = headA.next;//将首结点下移一个代表真正的首结点System.out.println(headA.toString());ListNode headB = new ListNode(0,null);pre = headB;while (sc2.hasNextInt()){ListNode curr = new ListNode(sc2.nextInt(), null);pre.next = curr;pre = curr;}headB = headB.next;//将首结点下移一个代表真正的首结点System.out.println(headB.toString());System.out.println("Reference of the node with value = "+getIntersectionNode(headA, headB).val);}
因为这个测试方法返回的永远是null,所以报了空指针异常。