Problem: 160. 相交链表
思路
先找出长度查,再一起移动cur指针
解题方法
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-X34yz1S4-1679156665038)(https://pic.leetcode.cn/1679153298-QgURQr-%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20230318225431.jpg)]
复杂度
- 时间复杂度:
O ( n ) O(n) O(n)
- 空间复杂度:
O ( 1 ) O(1) O(1)
Code
/**
* 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 curA = headA;
ListNode curB = headB;
int lengthA = 0;
int lengthB = 0;
while(curA != null){
curA = curA.next;
lengthA++;
}
while(curB != null){
curB = curB.next;
lengthB++;
}
curA = headA;
curB = headB;
//让A为长链表
if(lengthB > lengthA){
int tmpLen = lengthA;
lengthA = lengthB;
lengthB = tmpLen;
ListNode tmpNode = curA;
curA = curB;
curB = tmpNode;
}
int gsp = lengthA -lengthB;
while(gsp-- > 0){
curA = curA.next;
}
while(lengthB-- > 0){
if(curA == curB){
return curA;
}
curA = curA.next;
curB = curB.next;
}
return null;
}
}