這道題有多種算法。 算法1:把第一個鏈表逐項存在hashtable中,遍歷第2個鏈表的每一項,如果能在第一個鏈表中找到,則必然相交。
static bool JudgeIntersectLink1(Link head1, Link head2){Hashtable ht = new Hashtable();Link curr1 = head1;Link curr2 = head2;//store all the elements of link1while (curr1.Next != null){ht[curr1.Next] = string.Empty;curr1 = curr1.Next;}//check all the elements in link2 if exists in Hashtable or notwhile (curr2.Next != null){//if existsif (ht[curr2.Next] != null){return true;}curr2 = curr2.Next;}return false;}算法2:把一個鏈表A接在另一個鏈表B的末尾,如果有環,則必然相交。如何判斷有環呢?從A開始遍歷,如果能回到A的表頭,則肯定有環。 注意,在返回結果之前,要把剛才連接上的兩個鏈表斷開,恢復原狀。
static bool JudgeIntersectLink2(Link head1, Link head2){bool exists = false;Link curr1 = head1;Link curr2 = head2;//goto the end of the link1while (curr1.Next != null){curr1 = curr1.Next;}//join these two linkscurr1.Next = head2;//iterate link2while (curr2.Next != null){if (curr2.Next == head2){exists = true;break;}curr2 = curr2.Next;}//recover original status, whether exists or notcurr1.Next = null;return exists;}算法3:如果兩個鏈表的末尾元素相同,則必相交。
static bool JudgeIntersectLink3(Link head1, Link head2){Link curr1 = head1;Link curr2 = head2;//goto the end of the link1while (curr1.Next != null){curr1 = curr1.Next;}//goto the end of the link2while (curr2.Next != null){curr2 = curr2.Next;}if (curr1 != curr2)return false;elsereturn true;}新聞熱點
疑難解答