我在下面有以下小提琴,我试图在两个链接列表中找到交集: https://jsfiddle.net/youngfreezy/cj54vtcx/
它适用于大小相同的列表,但是我无法弄清楚它为什么不适用于不同长度的列表。我推进了较长列表的指针(以解释长度的不同),但在检查值时出现了问题。这是一个链表清单的例子:
我的方法如下:
这是我的主要功能:
LinkedList.prototype.isIntersection = function (LL1, LL2) {
var tail1 = LL1.tail;
var tail2 = LL2.tail;
var length1 = LL1.getLength(LL1.head);
var length2 = LL2.getLength(LL2.head);
if (tail1.val !== tail2.val) {
return false;
}
var shorter = ((length1 > length2) ? LL2 : LL1);
var longer = ((length1 > length2) ? LL1 : LL2);
var difference = Math.abs(length1 - length2);
if (difference > 0) {
//advance the longer one if there's a difference. this works.
longer = this.advanceToKthNode(longer, difference);
console.log(longer)
}
//point to the heads so you can iterate.
var shortIterator = shorter.head;
// this dosn't have a head if you advanced it.
var longIterator = longer.head || longer.val;
console.log(longIterator);
// console.log(shortIterator);
var intersection = "No Intersection";
//don't count the tail as an intersection.
while (longIterator && shortIterator && (longIterator !== longer.tail)) {
console.log("LONG", longIterator)
console.log("SHORT", shortIterator)
if (longIterator.val === shortIterator.val) {
intersection = longIterator.val;
}
shortIterator = shortIterator.next;
longIterator = longIterator.next;
}
// while ((longIterator && shortIterator)&&longIterator.val !== shortIterator.val) {
// // console.log(longIterator);
// shortIterator = shortIterator.next;
// longIterator = longIterator.next;
// }
return intersection;
};