【刷題1】LeetCode 160. 相交連結串列 java題解
阿新 • • 發佈:2020-12-19
https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
/**
* 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) {
if(headA==null||headB==null)
return null;
ListNode a=headA,b=headB;
while(a!=null&&b!=null){
a=a.next;
b=b.next;
}
int count1=0;
int count2=0;
while(a!=null){
count1++;
a=a.next;
}
while(b!=null){
count2++;
b=b.next;
}
a=headA;
b=headB;
while(count1>0){
a=a.next;
count1--;
}
while(count2>0) {
b=b.next;
count2--;
}
while(a!=null&&a!=b){
a=a.next;
b=b.next;
}
return a;
}
}
O(n) 時間複雜度,且僅用 O(1) 記憶體。