2017-02-01 62 views
0

我有以下節點的構造函數:在雙鏈表交換節點導致無限遞歸

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方法一個愚蠢的邏輯錯誤,但我不能爲我的生活找出什麼。

+1

find()函數在哪裏? – Pointy

+1

@Pointy編輯帖子以顯示查找方法 –

+0

我認爲您需要在重新分配之前爲這兩個條目獲取'.previous.next'的值。 – Pointy

回答

1

我看到的問題是在你的插入函數中。如果你有兩個項目的鏈接列表,並調用插件(「新節點」,NULL)列表如下:

enter image description here

你仍然需要以前的指針設置爲這樣的新節點:

LinkedList.prototype.insert = function(item,after){ 
    const newNode = new Node(item); 
    const curr = after ? this.find(after) : this.head; 
    newNode.next = curr.next; 
    curr.next.previous = newNode; <----- This is the extra line 
    newNode.previous = curr; 
    curr.next = newNode; 
} 
0

如果bNode.previousnull,如果你指定爲以下,

aNode.previous = bPrevious 
    aNode.previous.next = aNode 

,那麼你要訪問的nullnext場,這會導致崩潰。

+0

我不明白爲什麼'null'會導致無限遞歸。它應該只是拋出一個錯誤。 –

+0

你爲什麼認爲它會導致「無限遞歸」?由於您沒有提供錯誤或您在終端中看到的內容,所以我無法從您的問題中得知。 – ilke444