Node next; int val; public Node(int val) { this.val = val; }
public class ListNode {
public class ListNode{ int value; ListNode next; ListNode(int x){ value = x; next = null; } } public class Solution{ public ListNode getIntersectionNode(ListNode headA, ListNode headB){ ListNode l1 = headA, l2 = headB; while(l1 != l2){ l1 = (l1 == null)? headB : l1.next; l2 = (l2 == null)? headA : l2.next; } return l1; } }
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode *hA = headA; ListNode *hB = headB; if (!hA || !hB){ return NULL; } while (hA && hB && hA!=hB){ hA = hA -> next; hB = hB -> next; if (hA == hB){ break; } if(!hA){ hA = headB; } if(!hB){ hB = headA; } } return hA; } };参考:https://www.cnblogs.com/zhanzq/p/10563156.html