160. 相交链表
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int sizeA=0,sizeB=0;
ListNode tA=headA,tB=headB;
while(tA!=null){
tA=tA.next;
sizeA++;
}
while(tB!=null){
tB=tB.next;
sizeB++;
}
tA=headA;tB=headB;
if(sizeA>=sizeB){//移位
for(int i=sizeA-sizeB;i>0;i--){
tA=tA.next;
}
}else{
for(int i=sizeB-sizeA;i>0;i--){
tB=tB.next;
}
}
while(tA!=tB){
if(tA==null)return null;
tA=tA.next;tB=tB.next;
}
return tA;
}
19. 删除链表的倒数第 N 个结点
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head.next==null)return null;
int size=0;
ListNode t=head;
while(t!=null){t=t.next;size++;}
if(n==size){
return head.next;
}
t=head;
for(int i=size-n;i>1;i--){
t=t.next;
}
t.next=t.next.next;
return head;
}
142. 环形链表 II
快慢指针
判断一定要写全
public ListNode detectCycle(ListNode head) {
ListNode step1=head,step2=head;
while(step1!=null&&step2!=null){
step1=step1.next;
if(step2.next!=null)step2=step2.next.next;
else return null;
if(step1==step2){
step2=head;
while(step2!=step1){
step1=step1.next;
step2=step2.next;
}return step2;
}
}
return null;
}