leetcode 兩個鍊錶相交的一系列問題

2021-10-02 04:23:34 字數 1751 閱讀 8557

}//不用hash表返回入環中第乙個節點

public

static

getloopnode

(node head)

node n1=head.next;

//n1->slow

node n2=head.next.next;

//n2->fast

while

(n1!=n2)

n2=n2.next.next;

n1=n1.next;

}//當他們相同的時候跳出來,一步步走

n2=head;

while

(n1!=n2)

return n1;

//再次相同的點就是初始的結點

}public

static node noloop

(node head1, node head2)

node cur1 = head1;

node cur2 = head2;

int n =0;

while

(cur1.next != null)

while

(cur2.next != null)

if(cur1 != cur2)

cur1 = n >

0? head1 : head2;

cur2 = cur1 == head1 ? head2 : head1;

n = math.

abs(n)

;while

(n !=0)

while

(cur1 != cur2)

return cur1;

}//兩個有環鏈表相交

public

static node bothloop

(node head1, node loop1, node head2, node loop2)

while

(cur2 != loop2)

cur1 = n >

0? head1 : head2;

cur2 = cur1 == head1 ? head2 : head1;

n = math.

abs(n)

;while

(n !=0)

while

(cur1 != cur2)

return cur1;

}else

cur1 = cur1.next;

}return null;}}

public

static

void

main

(string[

] args)

}先存上,回頭再認真總結

如何判斷兩個鍊錶相交

方法一 最笨的方法,遍歷鍊錶1,每遍歷乙個節點,判斷這個節點是否在鍊錶2中 for node1 in l1 for node2 in l2 if node1 node2 return true 時間複雜度比較高,o l1.length l2.length 方法二 萬能的hash,對於節點位址進行ha...

LeetCode 鍊錶 相交鍊錶

語言 python 難度 簡單 描述 找到兩個單鏈表的重合鏈。比如 node a 4,1,8,4,5 node b 5,0,1,8,4,5 則這兩個鍊錶的起始節點為8,重合鏈為 8,4,5 node a 4,1,7,2,1 node b 5,0,1,8,4,5 則這兩個鍊錶的起始節點為null,不存...

兩鍊錶相交問題

1 兩個鍊錶相交,那麼兩個鍊錶中的節點一定有相同位址。2 兩個鍊錶相交,那麼兩個鍊錶從相交節點開始到尾節點一定都是相同的節點。問 為什麼?答 因為每乙個節點最多只能有乙個下一節點,因此在相交節點之後,鍊錶不可能再分為兩個鍊錶 根據兩個鍊錶是否存在環來分類討論 無環的情況有兩種比較快速的解決方式,這兩...