给定一个单向链表,我想用前一个节点的值更新每个元素的值,例如,如果我有列表1 - > 2 - > 3 - > null,所以在运行之后它将是 new_value - > 1 - > 2 - > null在每次迭代中给出 new_value 。
我试图做的(伪代码)是:
list_head = head
for i = length-1 to 0:
current = head
do i times:
prev_data = current.data
current = current.next
current.data = prev_data
它似乎没有正常工作,但是......我错过了什么?还有其他办法吗?
编辑:假设此时已将 new_value 分配到头部
提前致谢
答案 0 :(得分:0)
您也可以使用数组实现列表。这是javascript中的一个实现。希望它有所帮助。
var array = [1,2,3]; // list with array
var newValue = 4;
function push(value){
array.pop(); // to remove the last element
array.unshift(value); // to add the new element
console.log(array);
}
push(newValue);
答案 1 :(得分:0)
我没有看到你需要使用两个循环的原因 - 我怀疑你的问题与“做我时代”有关。相反,我建议只需将值推送到列表中,直到到达尾部(并删除最后一个值)。以下是使用非常简单的Node
类实现该想法:
function Node(data,next=null) {
this.data = data;
this.next = next;
this.toString = function() {
if(this.next) return this.data + " -> " + this.next.toString();
else return this.data + " -> null";
}
}
var head = new Node(1,new Node(2,new Node(3)));
console.log(head.toString())
var new_value = 0;
var curr = head;
do{
var old_value = curr.data;
curr.data = new_value;
new_value = old_value;
curr = curr.next;
} while(curr)
console.log(head.toString());