思路如下:
我们发现A、B链表长度可能不一样,我们可以用一个办法来使得两个链表遍历走过的长度一样:
假设从A头节点出发,向后遍历直到出现空结点,然后将下一个结点设为B的头节点;同理对B。那么当出现headA结点与headB结点相等的时候,就是相交点,此时两种方式走过的长度相等。
/**
* 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) {
if(headA==null||headB==null){
return null;
}
ListNode tempA=headA;
ListNode tempB=headB;
while(headA!=headB){
//为空,则接到另一个链表的头结点,否则继续向下遍历
headA=headA==null?tempB:headA.next;
headB=headB==null?tempA:headB.next;
}
return headA;
}
}
原题地址:
160. 相交链表