知识大全 判断两个单链表是否相交
Posted 知
篇首语:一身转战三千里,一剑曾当百万师。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 判断两个单链表是否相交相关的知识,希望对你有一定的参考价值。
这道题有多种算法 算法 把第一个链表逐项存在hashtable中 遍历第 个链表的每一项 如果能在第一个链表中找到 则必然相交 static bool JudgeIntersectLink (Link head Link head ) Hashtable ht = new Hashtable(); Link curr = head ; Link curr = head ; //store all the elements of link while (curr Next != null) ht[curr Next] = string Empty; curr = curr Next; //check all the elements in link if exists in Hashtable or not while (curr Next != null) //if exists if (ht[curr Next] != null) return true; curr = curr Next; return false;
算法 把一个链表A接在另一个链表B的末尾 如果有环 则必然相交 如何判断有环呢?从A开始遍历 如果能回到A的表头 则肯定有环 注意 在返回结果之前 要把刚才连接上的两个链表断开 恢复原状 static bool JudgeIntersectLink (Link head Link head ) bool exists = false; Link curr = head ; Link curr = head ;
//goto the end of the link while (curr Next != null) curr = curr Next; //join these o links curr Next = head ; //iterate link while (curr Next != null) if (curr Next == head ) exists = true; break; curr = curr Next; //recover original status whether exists or not curr Next = null; return exists;
cha138/Article/program/sjjg/201405/30738相关参考