思路
兩條鏈表長短不一,找公共交點必須先對齊。記錄兩個鏈表各自長度,長的向短的看齊,長的先走多出來的那么一截,之后兩者一起走,直到相遇或抵達末尾
代碼
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) {* val = x;* next = null;* }* }*/
public class Solution {public ListNode getIntersectionNode(ListNode headA, ListNode headB) {int a=0,b=0;ListNode temp=headA;while(temp!=null){++a;temp=temp.next;}temp=headB;while(temp!=null){++b;temp=temp.next;}if(a>b){temp=headA;for(int i=0;i<a-b;++i){temp=temp.next;}ListNode t=headB;while(t!=temp){t=t.next;temp=temp.next;}}else{
temp=headB;for(int i=0;i<b-a;++i){temp=temp.next;}ListNode t=headA;while(t!=temp){t=t.next;temp=temp.next;}}return temp;}
}