2016-11-09 180 views
0

我正在JavaScript中實現一個鏈接列表,並試圖在鏈表中的第n個位置插入一個元素。我可以插入一個元素;然而,名單的剩餘部分被切斷。例如,如果我有一個像a b f m這樣的列表並在2處插入c,如果我插入和打印,我的列表是a b cf m被切斷。在第n個位置插入元素

這裏是我的功能:

List.prototype.insertNth = function(index, data){ 
    this.head = this.head.insert(this.head, index, data) 
} 

Node.prototype.insert = function(head, index, data){ 
    if(index===0){ 
    var node = new Node(data, head) 
    return node 
    } 
    head.next = this.insert(head.next, index-1, data) 
    return head 
} 

和我打電話insertNth這樣list.insertNth(2, "c")。爲什麼在插入一個新節點後,剩餘的部分被切斷?

回答

1

當前插入節點的下一個下一個必須設置爲當前第N個節點。 這是通過添加

node.next = head 

做那麼只有它會鏈接到以下節點

List.prototype.insertNth = function(index, data){ 
this.head = this.head.insert(this.head, index, data) } 
Node.prototype.insert = function(head, index, data){ 
if(index===0){ 
var node = new Node(data, head) 
node.next = head 
return node 
} 
head.next = this.insert(head.next, index-1, data) 
return head } 
+1

這工作。謝謝。 –

相關問題