(LeetCode160)相交链表
题目描述:编写一个程序,找到两个单链表相交的起始节点。如图:
思路:
- 分别求出两个链表的长度,用长的减去短的就是长链表应该先走的步数
- 两个链表的节点同时移动,知道相遇则说明链表相交,若有链表走到空也没有相遇则说明没有相交,返回 null。
如上图,链表 A 的长度为 5 ,链表 B 的长度为 6,相减得到 diff = 1,则让较长的链表 B 走一步,到达 b2 节点,此时遍历 A, B两个链表,判断是否相交。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public int getLength(ListNode head){
int len = 0;
for(head = head;head != null;head = head.next){
len++;
}
return len;
}
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int lenA = getLength(headA);
int lenB = getLength(headB);
int diff = lenA - lenB;
ListNode longer = headA;
ListNode shorter = headB;
if(diff < 0){
longer = headB;
shorter = headA;
diff = -diff;
}
for(int i = 0;i < diff;i++){
longer = longer.next;
}
while(longer != shorter){
longer = longer.next;
shorter = shorter.next;
}
return longer;
}
}