Worked example and algorithm walkthrough
Topic: Linked Lists · Singly and doubly linked lists
Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.
Example input
{
"a": [
1,
2,
3
],
"op": "insert",
"doubly": false
}Execution steps
- Initial links
- Splice new node between neighbors
- Final head
Computed output
[ 1, 9, 2, 3 ]
JavaScript reference implementation
const solve = ({
a,op,doubly
},s)=>{
let nodes=a.map((v,i)=>({
v,next:i+1<a.length?i+1:-1,prev:i-1
})),head=0;
function emit(msg){
s(msg,{
Nodes:nodes.map((x,i)=>i+":"+x.v+" → "+x.next+(doubly?" ← "+x.prev:"")),Head:[head]
})
}
emit("Initial links");
if(op==="insert"){
nodes.push({
v:9,next:1,prev:0
});
nodes[0].next=3;
if(doubly)nodes[1].prev=3;
emit("Splice new node between neighbors")
}else if(op==="delete"){
nodes[0].next=2;
if(doubly)nodes[2].prev=0;
nodes[1].next=-1;
nodes[1].prev=-1;
emit("Bypass removed node")
}else if(op==="reverse"){
for(let i=0;
i<nodes.length;
i++){
[nodes[i].next,nodes[i].prev]=[nodes[i].prev,nodes[i].next];
emit("Swap next and previous links")
}
head=nodes.length-1
}else{
function rev(i){
if(nodes[i].next===-1)return i;
let j=nodes[i].next,h=rev(j);
nodes[j].next=i;
nodes[i].next=-1;
emit("Reverse return link "+j+" → "+i);
return h
}
head=rev(head)
}
emit("Final head");
let o=[];
for(let i=head;
i!==-1;
i=nodes[i].next)o.push(nodes[i].v);
return o
};