相交链表
方法一
刚看题目没有头绪,想到之前写的链表倒数第k个节点,首先遍历链表,找到链表长度,通过两个链表长度的差使链表末端对齐。通过对末端对齐后的两链表同时遍历,对比下一节点是否相同判断结果。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode a = headA;
ListNode b = headB;
ListNode A = new ListNode();
ListNode B = new ListNode();
A.next = headA;
B.next = headB;
int numa = 0, numb = 0;
int len = 0;
while(a != null){
numa++;
a = a.next;
}
while(b != null){
numb++;
b = b.next;
}
len = numa - numb;
if(len > 0){
while(len > 0){
A = A.next;
len--;
}
while(A != null && B != null){
if(A.next == B.next) return A.next;
A = A.next;
B = B.next;
}
return null;
}else{
len = -len;
while(len > 0){
B = B.next;
len--;
}
while(A != null && B != null){
if(A.next == B.next) return A.next;
A = A.next;
B = B.next;
}
return null;
}
}
}
方法二
先便利自身的链表,再遍历另一个链表
原因如下:
若有公共部分
公共部分的长度为c,链表一长度为a,链表b长度为b
则两个指针同时指到公共节点需要走过的长度为
a + (b - c)和 b + (a - c)
到公共部分就会停止,返回a或b都可
若没有公共部分,此时为图所示,最后所指的都为null,与题意相符,返回null即可。
/**
* 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 a = headA;
// ListNode b = headB;
// ListNode A = new ListNode();
// ListNode B = new ListNode();
// A.next = headA;
// B.next = headB;
// int numa = 0, numb = 0;
// int len = 0;
// while(a != null){
// numa++;
// a = a.next;
// }
// while(b != null){
// numb++;
// b = b.next;
// }
// len = numa - numb;
// if(len > 0){
// while(len > 0){
// A = A.next;
// len--;
// }
// while(A != null && B != null){
// if(A.next == B.next) return A.next;
// A = A.next;
// B = B.next;
// }
// return null;
// }else{
// len = -len;
// while(len > 0){
// B = B.next;
// len--;
// }
// while(A != null && B != null){
// if(A.next == B.next) return A.next;
// A = A.next;
// B = B.next;
// }
// return null;
// }
ListNode a = headA;
ListNode b = headB;
while(a != b){
a = a != null ? a.next : headB;
b = b != null ? b.next : headA;
}
return a;
}
}