编写一个程序,找到两个单链表相交的起始节点。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法其一:
思路:获取两个单链表L1,L2的长度,如L1长于L2,则L1 head往后走L1-L2个节点
/**
* 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) {
ListNode node1 = headA;
ListNode node2 = headB;
int length1=0,length2=0;
while(node1!=null){
length1++;
node1 = node1.next;
}
while(node2!=null){
length2++;
node2 = node2.next;
}
node1 = headA;
node2 = headB;
if(length1>length2){
for(int i=0;i<length1-length2;i++){
node1 = node1.next;
}
}else{
for(int i=0;i<length2-length1;i++){
node2 = node2.next;
}
}
while(node1!=null){
if(node1!=node2){
node1=node1.next;
node2=node2.next;
}else{
return node1;
}
}
return null;
}
}