解题思路:
- 计算长度
- A代表最长的链表
- 尾部对齐
- 判断
错误点:
- 没赋值初始化的值
- 没定义类型
- 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) {
ListNode curA=headA;
ListNode curB=headB;
int lenA=0,lenB=0;
//计算AB长度
while(curA!=null){
lenA++;
curA=curA.next;
}
while(curB!=null){
lenB++;
curB=curB.next;
}
curA=headA;
curB=headB;
//链表A代表最长的链表
if(lenB>lenA){
ListNode tmpNode=headA;//headA和headB表示地址/指针
headA=headB;
headB=tmpNode;
curA=headA;//不需要临时指针,直接指向头节点
curB=headB;
int tmplen=lenA;
lenA=lenB;
lenB=tmplen;
}
//尾部对齐
int gap=lenA-lenB; //没有定义类型
while(gap-- >0){
curA=curA.next;
}
while(curA!=null){
if(curA==curB){ //判断运算符
return curA;
}
curA=curA.next;
curB=curB.next;
}
return null;
}
}