我有以下節點的構造函數:在雙鏈表交換節點導致無限遞歸
const Node = function(data){
this.data = data
this.next = null
this.previous = null
}
是用我的LinkedList構造函數的內部:
const LinkedList = function(){
this.head = new Node('head')
}
,我可以插入節點與以下方法:
LinkedList.prototype.insert = function(item,after){
const newNode = new Node(item)
const curr = after ? this.find(after) : this.head
newNode.next = curr.next
newNode.previous = curr
curr.next = newNode
}
與find
方法是:
LinkedList.prototype.find = function(item){
let currentNode = this.head
while(currentNode && currentNode.data !== item){
currentNode = currentNode.next
}
return currentNode
}
並可以查看的項目用如下方法的數組:
LinkedList.prototype.toArray = function(){
const arr = []
let currItem = this.head.next
while(currItem){
arr.push(currItem.data)
currItem = currItem.next
}
return arr
}
我的問題,現在我想實現的LinkedList的一個switch
功能,我可以在兩個值傳遞和將它們的位置切換到列表中。下面是我有什麼,似乎對於那些不相鄰的其他項目的工作:
LinkedList.prototype.switch = function(a,b){
const aNode = this.find(a),
bNode = this.find(b)
if(!aNode || !bNode){
throw new Error('Both nodes were not inside of the list')
}
const aNext = aNode.next,
aPrevious = aNode.previous,
bNext = bNode.next,
bPrevious = bNode.previous
aNode.next = bNext
aNode.previous = bPrevious
aNode.previous.next = aNode
bNode.next = aNext
bNode.previous = aPrevious
bNode.previous.next = bNode
}
我想知道我在做什麼錯在這裏,是造成這使我的電腦打無限遞歸的時候我換相鄰的元素。例如,代碼的下面行工作:
const list = new LinkedList()
list.insert(1)
list.insert(2,1)
list.insert(3,2)
list.switch(1,3)
list.toArray() // [3,2,1]
但是如果我有下面的代碼,它
const list = new LinkedList()
list.insert(1)
list.insert(2,1)
list.switch(1,2)
list.toArray() // crashes terminal
我知道這是我switch
方法一個愚蠢的邏輯錯誤,但我不能爲我的生活找出什麼。
find()函數在哪裏? – Pointy
@Pointy編輯帖子以顯示查找方法 –
我認爲您需要在重新分配之前爲這兩個條目獲取'.previous.next'的值。 – Pointy