面试题 02.07. 链表相交
一定要注意是结点相同,而不是数值相同。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode newA = new ListNode(0,headA);
ListNode newB = new ListNode(0,headB);
ListNode left = headA;
ListNode right = headB;
int coutA = 0;
int coutB = 0;
while (left != null){
coutA++;
left = left.next;
}
while (right != null){
coutB++;
right = right.next;
}
left = headA;
right = headB;
int gap = coutA>coutB?coutA-coutB:coutB-coutA;
if(coutA > coutB){
for (int i = 0; i < gap; i++) {
left = left.next;
}
}
else {
for (int i = 0; i < gap; i++) {
right = right.next;
}
}
while (left != null){
if(left == right)
return left;
left = left.next;
right = right.next;
}
return null;
}
}
一种很优美的代码做法:
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null ){
return null;
}
ListNode l1 = headA;
ListNode l2 = headB;
while(l1 != l2){
l1 = l1 == null ? headB : l1.next;
l2 = l2 == null ? headA : l2.next;
}
return l1;