如何通过JavaScript在链表中插入元素 我从LeetCode那里得到了这个问题
问题21,https://leetcode.com/problems/merge-two-sorted-lists/如何通过JavaScript在链表中插入元素 我从LeetCode那里得到了这个问题,javascript,algorithm,ecmascript-6,linked-list,Javascript,Algorithm,Ecmascript 6,Linked List,问题21,https://leetcode.com/problems/merge-two-sorted-lists/ 但这不仅仅是为了解决这个问题 这是我对问题的描述,我有一个原始的链表[1,2,4],它的数据结构如下: function ListNode(val, next) { this.val = (val===undefined ? 0 : val) this.next = (next===undefined ? null : next) } 我想在2之
但这不仅仅是为了解决这个问题 这是我对问题的描述,我有一个原始的链表[1,2,4],它的数据结构如下:
function ListNode(val, next) {
this.val = (val===undefined ? 0 : val)
this.next = (next===undefined ? null : next)
}
我想在2之后插入3,并使其成为[1,2,3,4]。几乎从我读过的所有教程中,他们都告诉我这样做:
var insert = function(l1) {
let i=0;
let p = l1;
while(i<1 && p){
p = p.next;
i++;
}
let tem = new ListNode(3,p.next);
p.next = tem;
return p;
};
var插入=函数(l1){
设i=0;
设p=l1;
while(i您不应返回p
,而应返回lst
我当然建议不要在函数中硬编码值和循环条件,而是将它们作为参数传递给函数
另外,当您要调用insert
在列表的最开始插入值时,需要一段单独的代码:
函数ListNode(val=0,next=null){//使用默认值
this.val=val;
this.next=next;
}
变量插入=函数(l1,索引,值){
如果(索引==0)返回新的ListNode(值,l1);
设i=1;//从1开始
设p=l1;
请试试这个
class LinkedList{
constructor(val){
this.head = new ListNode(val);
this.tail = this.head;
}
add(val){
this.tail.next = new ListNode(val);
this.tail = this.tail.next;
}
insert(val, after){
let node = this;
while(node){
//find the node you want to insert after
if ( node.val === after){
//and create a new node, and q.next = p.next ;p.next = q
node.next = new ListNode(val, node.next);
//break
node = null;
} else {
//node is not fouund still
node = node.next;
}
}
}
}
class ListNode{
constructor(val, next) {
this.val = (val===undefined ? 0 : val);
this.next = (next===undefined ? null : next);
}
}
var list = new LinkedList(1);//1
list.add(2);//1->2
list.add(4);//1->2->4
list.insert(3,2);//1->2->3->4
提议的“算法”是什么是因为您不明白吗?为什么在第一次迭代后停止循环时停止?您甚至没有在列表中的哪个节点上进行测试。@Andreas很抱歉没有说清楚,我这样做是为了测试,为了直接获得节点2,我硬编码它。尝试并实现这一点,看看您得到了什么。Po如果您仍然有问题,请将代码作为一个片段保存在这里。这将使人们更容易帮助您。这正是我所误解的,非常感谢,明白了吗