Repository navigation
Expand file tree
/
Copy pathapp.html
More file actions
2166 lines (2120 loc) · 98.2 KB
/
Copy pathapp.html
File metadata and controls
2166 lines (2120 loc) · 98.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<title>Data Structures Studio</title>
<style>
/* Deliberate single-theme design: a dark neon lab. Every color painted explicitly. */
:root{
--paper:#0a0e17; --panel:#101624; --edge:#1f2a44; --ink:#dde6ff; --ink2:#8093bb;
--accent:#2dd6ff; --accent-soft:#0d2a3a; --cur:#ffb020; --cur-soft:#2b2008;
--fresh:#2fe6a0; --cut:#ff4d6d; --badge:#a78bfa; --node:#131b2e; --node-edge:#41547e;
--rbred:#ff4d6d; --rbblack:#0b0f1a; --rbtext:#eef2ff; --chip:#182238;
}
*{box-sizing:border-box; margin:0}
html,body{height:100%}
body{
background:var(--paper); color:var(--ink); overflow:hidden;
font:14px/1.4 "Segoe UI Variable Text","Segoe UI",system-ui,-apple-system,sans-serif;
}
#app{height:100vh; display:flex; flex-direction:column}
header.top{
display:flex; align-items:center; gap:16px; padding:8px 14px 0;
border-bottom:1px solid var(--edge); background:var(--panel); flex:none;
}
.brand{font-weight:700; letter-spacing:.16em; font-size:15px; padding-bottom:8px; white-space:nowrap; color:var(--accent); text-shadow:0 0 14px var(--accent-soft)}
.brand .sub{font-weight:400; letter-spacing:.02em; color:var(--ink2); font-size:12px; margin-left:8px}
@media (max-width: 1520px){ .brand .sub{display:none} }
@media (max-width: 1330px){ #tabs button{padding:9px 8px 11px; font-size:12px} .brand{letter-spacing:.1em} }
#tabs{display:flex; gap:2px; overflow-x:auto; scrollbar-width:none}
#tabs button{
appearance:none; border:0; background:none; color:var(--ink2); cursor:pointer;
font:600 12.5px/1 inherit; font-family:inherit; padding:9px 11px 11px; white-space:nowrap;
border-bottom:2px solid transparent;
}
#tabs button:hover{color:var(--ink)}
#tabs button.on{color:var(--accent); border-bottom-color:var(--accent); text-shadow:0 0 12px var(--accent)}
#tabs button:focus-visible,.deck button:focus-visible,.deck input:focus-visible{
outline:2px solid var(--accent); outline-offset:1px; border-radius:3px;
}
.deck{
display:flex; align-items:center; gap:14px; flex-wrap:nowrap;
padding:8px 14px; background:var(--panel); border-bottom:1px solid var(--edge); flex:none;
}
.deck label{display:flex; align-items:center; gap:6px; color:var(--ink2); font-size:12px; font-weight:600}
.deck input{
width:64px; padding:6px 8px; border:1px solid var(--edge); border-radius:5px;
background:var(--paper); color:var(--ink); caret-color:var(--accent);
font:600 13.5px "Cascadia Code",Consolas,ui-monospace,monospace;
}
.deck input:focus{outline:none; border-color:var(--accent); box-shadow:0 0 8px var(--accent-soft), 0 0 0 1px var(--accent)}
#ops{display:flex; gap:8px; flex-wrap:wrap}
.opgrp{
display:inline-flex; align-items:center; gap:1px;
background:var(--chip); border:1px solid var(--edge); border-radius:7px; padding:2px 3px 2px 0;
}
.opgrp .glabel{font-size:10px; font-weight:800; letter-spacing:.14em; color:var(--ink2); margin:0 6px 0 10px; user-select:none}
.opgrp[data-grp="add"] .glabel{color:var(--fresh)}
.opgrp[data-grp="del"] .glabel{color:var(--cut)}
.opgrp[data-grp="etc"] .glabel{color:var(--badge)}
.opgrp[data-grp="data"] .glabel{color:var(--accent)}
#ops button{
appearance:none; cursor:pointer; border:0; border-radius:5px;
background:transparent; color:var(--ink); font:600 13px/1 inherit; font-family:inherit;
padding:8px 11px; white-space:nowrap;
}
#ops button:hover:not(:disabled){background:var(--panel); color:var(--accent); box-shadow:inset 0 0 0 1px var(--edge)}
.opgrp[data-grp="del"] button:hover:not(:disabled){color:var(--cut)}
.opgrp[data-grp="add"] button:hover:not(:disabled){color:var(--fresh)}
#ops button:disabled{opacity:.35; cursor:default}
.run{display:flex; align-items:center; gap:8px; margin-left:auto}
.run button{
appearance:none; cursor:pointer; border:1px solid var(--edge); border-radius:5px;
background:transparent; color:var(--ink); font:600 12px/1 inherit; font-family:inherit;
padding:6px 10px; white-space:nowrap;
}
.run button:hover:not(:disabled){border-color:var(--accent); color:var(--accent)}
.run button:disabled{opacity:.35; cursor:default}
.run select{
appearance:none; cursor:pointer; border:1px solid var(--edge); border-radius:5px;
background:var(--chip); color:var(--accent); font:600 12px/1 inherit; font-family:inherit;
padding:7px 9px; max-width:190px;
}
.run select:hover:not(:disabled){border-color:var(--accent)}
.run select:disabled{opacity:.35; cursor:default}
.run select option{background:var(--panel); color:var(--ink)}
.run input[type=range]{width:90px; accent-color:var(--accent)}
.run .rlabel{font-size:11px; color:var(--ink2); font-weight:600}
main#stage{flex:1 1 0; min-height:0; position:relative}
#svg{position:absolute; inset:0; width:100%; height:100%; display:block}
body.logopen #svg{width:calc(100% - 292px)}
#log{
position:absolute; top:8px; right:8px; bottom:8px; width:280px; display:none;
flex-direction:column; background:var(--panel); border:1px solid var(--edge); border-radius:6px;
}
body.logopen #log{display:flex}
#log header{
display:flex; align-items:center; justify-content:space-between;
padding:7px 10px; border-bottom:1px solid var(--edge);
font:700 10.5px inherit; font-family:inherit; letter-spacing:.12em; color:var(--ink2);
}
#log header button{appearance:none; border:0; background:none; color:var(--ink2); cursor:pointer; font-size:14px; line-height:1; padding:0 2px}
#log header button:hover{color:var(--ink)}
#logbody{flex:1; overflow-y:auto; padding:6px 8px; display:flex; flex-direction:column; gap:5px; scrollbar-width:thin; scrollbar-color:var(--edge) transparent}
.lentry{display:flex; gap:7px; align-items:baseline; font-size:12.5px; line-height:1.5; color:var(--ink)}
.lentry .lstep{
flex:none; min-width:20px; text-align:right; color:var(--cur);
font:700 11px "Cascadia Code",Consolas,ui-monospace,monospace; font-variant-numeric:tabular-nums;
}
.lentry b{color:var(--accent)}
.lentry.ldone{border-top:1px dashed var(--edge); padding-top:5px; margin-top:2px}
.lentry.ldone p{color:var(--accent); font-weight:650}
.lentry p{margin:0}
#msg code, .lentry code{
background:var(--chip); color:var(--accent); border-radius:3px; padding:1px 5px;
font:600 11px "Cascadia Code",Consolas,ui-monospace,monospace; white-space:nowrap;
}
.lentry code{white-space:pre-wrap; overflow-wrap:anywhere; display:inline}
.node rect,.node circle{fill:var(--node); stroke:var(--node-edge); stroke-width:1.5}
.node text{
fill:var(--ink); font:600 16px "Cascadia Code",Consolas,ui-monospace,monospace;
text-anchor:middle; dominant-baseline:central;
}
.node.hl rect,.node.hl circle{stroke:var(--cur); stroke-width:3; fill:var(--cur-soft); filter:drop-shadow(0 0 7px var(--cur))}
.node.hit rect,.node.hit circle{stroke:var(--fresh); stroke-width:3; filter:drop-shadow(0 0 7px var(--fresh))}
.node.doom rect,.node.doom circle{stroke:var(--cut); stroke-width:3; stroke-dasharray:5 3; filter:drop-shadow(0 0 7px var(--cut))}
.node.rb-r circle{fill:var(--rbred); stroke:var(--rbred)}
.node.rb-r text{fill:var(--rbtext)}
.node.rb-b circle{fill:var(--rbblack); stroke:var(--node-edge)}
.node.rb-b text{fill:var(--rbtext)}
.node .tag{font:600 10px "Cascadia Code",Consolas,ui-monospace,monospace; fill:var(--ink2)}
.edge{stroke:var(--node-edge); stroke-width:1.6; fill:none}
.edge.fresh{stroke:var(--fresh); stroke-width:2.6; filter:drop-shadow(0 0 4px var(--fresh))}
.edge.dying{stroke:var(--cut); stroke-width:2.2; stroke-dasharray:6 4; filter:drop-shadow(0 0 4px var(--cut))}
.edge.prevlane{opacity:.55}
.ptr text{font:700 11.5px "Cascadia Code",Consolas,ui-monospace,monospace; text-anchor:middle}
.ptr line{stroke-width:1.6}
.ptr.pcur text{fill:var(--cur); text-shadow:0 0 10px var(--cur)} .ptr.pcur line{stroke:var(--cur)}
.ptr.pbadge text{fill:var(--badge); text-shadow:0 0 10px var(--badge)} .ptr.pbadge line{stroke:var(--badge)}
.bucket rect{fill:none; stroke:var(--edge); stroke-width:1.2}
.bucket text{fill:var(--ink2); font:600 11px "Cascadia Code",Consolas,ui-monospace,monospace; text-anchor:middle; dominant-baseline:central}
.slotline{stroke:var(--edge); stroke-width:1}
.emptyhint{fill:var(--ink2); font:400 13px inherit; text-anchor:middle}
footer.status{
flex:none; display:flex; align-items:center; gap:14px;
padding:7px 14px; background:var(--panel); border-top:1px solid var(--edge);
}
#msg{flex:1 1 auto; min-width:0; font-size:13.5px; color:var(--ink); white-space:nowrap; overflow:hidden; text-overflow:ellipsis}
#msg b{color:var(--accent)}
#count{
flex:none; font:700 13.5px "Cascadia Code",Consolas,ui-monospace,monospace;
color:var(--cur); min-width:92px; text-align:right; font-variant-numeric:tabular-nums;
text-shadow:0 0 10px var(--cur);
}
#bigo{flex:none; display:flex; gap:6px}
#bigo span{
background:var(--chip); color:var(--ink2); border-radius:4px; padding:4px 8px;
border:1px solid var(--edge);
font:600 11.5px "Cascadia Code",Consolas,ui-monospace,monospace; white-space:nowrap;
}
#bigo span b{color:var(--accent); font-weight:700}
@media (prefers-reduced-motion: reduce){ #svg *{transition:none !important} }
</style>
<div id="app">
<header class="top">
<div class="brand">DATA STRUCTURES STUDIO<span class="sub">watch the links move</span></div>
<nav id="tabs" aria-label="Data structures"></nav>
</header>
<section class="deck">
<label>Value <input id="val" maxlength="4" spellcheck="false" placeholder="A1#"></label>
<label title="0-based — the first node is index 0">Index <input id="idx" type="number" min="0" step="1" value="0"></label>
<div id="ops"></div>
<div class="run">
<select id="tryit" aria-label="Guided experiments">
<option value="">⚗ Try this…</option>
<option value="tails">Delete tail: singly vs doubly</option>
<option value="trees">Search: BST chain vs AVL</option>
<option value="dist">Insert-at: distance = cost</option>
<option value="hash">Hash collisions</option>
</select>
<span class="rlabel">Speed</span>
<input type="range" id="speed" min="1" max="30" value="10" aria-label="Animation speed">
<button id="finish" title="Jump to end of animation">⏭ Finish</button>
<button id="logbtn" title="Show or hide the operation log">☰ Log</button>
</div>
</section>
<main id="stage">
<svg id="svg" role="img" aria-label="Data structure visualization"></svg>
<aside id="log" aria-label="Operation log">
<header>OPERATION LOG<button id="logx" aria-label="Close log">×</button></header>
<div id="logbody"></div>
</aside>
</main>
<footer class="status">
<div id="msg">Ready. Pick a structure, type a value, press an operation.</div>
<div id="count">steps: 0</div>
<div id="bigo"></div>
</footer>
</div>
<script>
'use strict';
/* ============ Structura core: recorder, renderer, player, UI ============ */
const SVGNS = 'http://www.w3.org/2000/svg';
const $ = s => document.querySelector(s);
let uid = 1;
const nid = () => 'n' + (uid++);
const SYMS = '#@$%&*+?!';
const ALNUM = 'ABCDEFGHJKMNPQRSTUVWXYZ0123456789';
function randToken() {
const r = Math.random();
if (r < 0.25) return ALNUM[Math.floor(Math.random() * ALNUM.length)] + SYMS[Math.floor(Math.random() * SYMS.length)];
if (r < 0.6) return ALNUM[Math.floor(Math.random() * ALNUM.length)] + ALNUM[Math.floor(Math.random() * ALNUM.length)];
return String(Math.floor(Math.random() * 99));
}
const COLL = new Intl.Collator(undefined, { numeric: true, sensitivity: 'variant' });
function cmp(a, b) {
// numeric-aware collation ("2" < "10"), refined by a code-point tiebreak so
// distinct strings are never equal ("02" and "2" are two different values)
const A = String(a), B = String(b);
const c = COLL.compare(A, B);
if (c) return c < 0 ? -1 : 1;
return A < B ? -1 : A > B ? 1 : 0;
}
const esc = v => String(v).slice(0, 4).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
const shortVal = v => String(v).slice(0, 4);
/* ---------------- Recorder ---------------- */
class Rec {
constructor() { this.steps = []; this.count = 0; }
note(text) { this.steps.push({ t: 'note', text, count: this.count }); }
tick(n = 1) { this.count += n; }
cur(id) { this.steps.push({ t: 'cur', id, count: this.count }); }
snap(struct, opts) { this.steps.push({ t: 'scene', scene: struct.scene(), count: this.count, slow: opts && opts.slow }); }
done(opName, big) { this.steps.push({ t: 'done', text: `${opName} — ${this.count} step${this.count === 1 ? '' : 's'} · ${big}`, count: this.count }); }
}
/* ---------------- Base structure ---------------- */
class Struct {
constructor() { this.fx = { hl: new Set(), hit: new Set(), doom: new Set(), fresh: new Set(), dying: new Set() }; }
sizeInfo() { return `n = ${this.n || 0}`; }
clearFx() { for (const k in this.fx) this.fx[k].clear(); }
snapFx(R, opts) { R.snap(this, opts); this.clearFx(); }
scene() { return { w: 100, h: 100, nodes: [], edges: [], ptrs: [], frames: [] }; }
edgeCls(a, b) {
const k = a + '>' + b;
if (this.fx.fresh.has(k)) return 'fresh';
if (this.fx.dying.has(k)) return 'dying';
return '';
}
nodeCls(id, base) {
let c = base || '';
if (this.fx.hl.has(id)) c += ' hl';
if (this.fx.hit.has(id)) c += ' hit';
if (this.fx.doom.has(id)) c += ' doom';
return c.trim();
}
}
/* ---------------- Renderer ---------------- */
class Renderer {
constructor(svg) {
this.svg = svg;
this.defs();
this.gFrames = this.layer(); this.gEdges = this.layer(); this.gNodes = this.layer(); this.gPtrs = this.layer();
this.nodes = new Map(); // id -> {x,y,tx,ty,alpha,talpha,el,txt,shapeEl,tagEl,scene}
this.edges = new Map(); // key -> {el, spec}
this.curId = null;
this.vb = { x: 0, y: 0, w: 400, h: 300 }; this.tvb = { ...this.vb };
this.sceneMeta = { w: 400, h: 300, frames: [], ptrs: [] };
this.hint = null;
this.rm = window.matchMedia ? window.matchMedia('(prefers-reduced-motion: reduce)') : null;
this._raf = this.frame.bind(this);
requestAnimationFrame(this._raf);
}
layer() { const g = document.createElementNS(SVGNS, 'g'); this.svg.appendChild(g); return g; }
defs() {
const d = document.createElementNS(SVGNS, 'defs');
d.innerHTML = ['', 'fresh', 'dying'].map(c => {
const id = 'arr' + (c || 'std');
return `<marker id="${id}" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
<path d="M0 0 L10 5 L0 10 z" class="mk-${c || 'std'}"></path></marker>`;
}).join('');
this.svg.appendChild(d);
const st = document.createElement('style');
st.textContent = '.mk-std{fill:var(--node-edge)} .mk-fresh{fill:var(--fresh)} .mk-dying{fill:var(--cut)}';
document.head ? document.head.appendChild(st) : document.body.appendChild(st);
}
applyScene(scene, instant) {
this.sceneMeta = scene;
const seen = new Set();
for (const n of scene.nodes) {
seen.add(n.id);
let vn = this.nodes.get(n.id);
if (!vn) {
const el = document.createElementNS(SVGNS, 'g');
const shapeEl = n.shape === 'circ'
? document.createElementNS(SVGNS, 'circle')
: document.createElementNS(SVGNS, 'rect');
if (n.shape === 'circ') { shapeEl.setAttribute('r', 21); }
else { shapeEl.setAttribute('x', -29); shapeEl.setAttribute('y', -18); shapeEl.setAttribute('width', 58); shapeEl.setAttribute('height', 36); shapeEl.setAttribute('rx', 5); }
const txt = document.createElementNS(SVGNS, 'text');
const tagEl = document.createElementNS(SVGNS, 'text');
tagEl.setAttribute('class', 'tag'); tagEl.setAttribute('text-anchor', 'middle'); tagEl.setAttribute('y', n.shape === 'circ' ? 36 : 32);
el.appendChild(shapeEl); el.appendChild(txt); el.appendChild(tagEl);
this.gNodes.appendChild(el);
vn = { x: n.x, y: n.y, tx: n.x, ty: n.y, alpha: 0, talpha: 1, el, txt, tagEl, shapeEl };
this.nodes.set(n.id, vn);
}
vn.tx = n.x; vn.ty = n.y; vn.talpha = 1; vn.dead = false;
if (instant) { vn.x = n.x; vn.y = n.y; vn.alpha = 1; }
vn.el.setAttribute('class', ('node ' + (n.cls || '')).trim());
vn.txt.textContent = shortVal(n.v);
vn.tagEl.textContent = n.tag || '';
}
for (const [id, vn] of this.nodes) {
if (!seen.has(id)) { vn.talpha = 0; vn.dead = true; if (instant) vn.alpha = 0; }
}
// edges: rebuild key set
const ekeys = new Set();
for (const e of scene.edges) {
const key = e.from + '>' + e.to + ':' + (e.kind || '') + ':' + (e.lane || '');
ekeys.add(key);
let ve = this.edges.get(key);
if (!ve) {
const el = document.createElementNS(SVGNS, 'path');
this.gEdges.appendChild(el);
ve = { el }; this.edges.set(key, ve);
}
ve.spec = e;
ve.el.setAttribute('class', ('edge ' + (e.cls || '') + (e.lane === 'prev' ? ' prevlane' : '')).trim());
ve.el.setAttribute('marker-end', `url(#arr${e.cls || 'std'})`);
}
for (const [key, ve] of this.edges) if (!ekeys.has(key)) { ve.el.remove(); this.edges.delete(key); }
// frames (static furniture)
this.gFrames.innerHTML = '';
for (const f of scene.frames || []) {
if (f.t === 'rect') {
const g = document.createElementNS(SVGNS, 'g'); g.setAttribute('class', 'bucket');
g.innerHTML = `<rect x="${f.x}" y="${f.y}" width="${f.w}" height="${f.h}" rx="4"></rect><text x="${f.x + f.w / 2}" y="${f.y + f.h / 2}">${f.label}</text>`;
this.gFrames.appendChild(g);
} else if (f.t === 'text') {
const t = document.createElementNS(SVGNS, 'text');
t.setAttribute('class', 'emptyhint'); t.setAttribute('x', f.x); t.setAttribute('y', f.y);
t.textContent = f.label; this.gFrames.appendChild(t);
}
}
// viewBox target
const pad = 56;
this.tvb = { x: scene.x0 - pad, y: scene.y0 - pad, w: scene.w + pad * 2, h: scene.h + pad * 2 };
if (instant) this.vb = { ...this.tvb };
}
setCur(id) { this.curId = id; }
frame() {
try { this.frameBody(); }
catch (err) { console.error(err); }
finally { requestAnimationFrame(this._raf); } // the render loop must survive anything
}
frameBody() {
const k = this.rm && this.rm.matches ? 1 : 0.16;
for (const [id, vn] of this.nodes) {
vn.x += (vn.tx - vn.x) * k; vn.y += (vn.ty - vn.y) * k;
vn.alpha += (vn.talpha - vn.alpha) * k;
if (Math.abs(vn.tx - vn.x) < .4) vn.x = vn.tx;
if (Math.abs(vn.ty - vn.y) < .4) vn.y = vn.ty;
if (Math.abs(vn.talpha - vn.alpha) < .02) vn.alpha = vn.talpha;
if (vn.dead && vn.alpha <= 0) { vn.el.remove(); this.nodes.delete(id); continue; }
vn.el.setAttribute('transform', `translate(${vn.x},${vn.y})`);
vn.el.setAttribute('opacity', vn.alpha.toFixed(3));
}
for (const [, ve] of this.edges) this.drawEdge(ve);
this.drawPtrs();
for (const p of ['x', 'y', 'w', 'h']) {
this.vb[p] += (this.tvb[p] - this.vb[p]) * k;
if (Math.abs(this.tvb[p] - this.vb[p]) < .5) this.vb[p] = this.tvb[p];
}
this.svg.setAttribute('viewBox', `${this.vb.x} ${this.vb.y} ${this.vb.w} ${this.vb.h}`);
}
anchor(vn, other, shape) {
// point on node boundary toward other node
const dx = other.x - vn.x, dy = other.y - vn.y;
const d = Math.hypot(dx, dy) || 1;
if (shape === 'circ') return { x: vn.x + dx / d * 23, y: vn.y + dy / d * 23 };
// rect 58x36
const rx = 31, ry = 20;
const sx = Math.abs(dx / d) < 1e-6 ? Infinity : rx / Math.abs(dx / d);
const sy = Math.abs(dy / d) < 1e-6 ? Infinity : ry / Math.abs(dy / d);
const s = Math.min(sx, sy);
return { x: vn.x + dx / d * s, y: vn.y + dy / d * s };
}
drawEdge(ve) {
const e = ve.spec;
const a = this.nodes.get(e.from), b = this.nodes.get(e.to);
if (!a || !b) { ve.el.setAttribute('d', ''); return; }
if (e.from === e.to) {
// self-loop (single-node ring): a visible loop below the node
const x = a.x, y = a.y + 18;
ve.el.setAttribute('opacity', a.alpha.toFixed(3));
ve.el.setAttribute('d', `M ${x - 12} ${y} C ${x - 36} ${y + 46}, ${x + 36} ${y + 46}, ${x + 12} ${y}`);
return;
}
const shA = e.shape || 'rect', shB = e.shape || 'rect';
let p1 = this.anchor(a, b, shA), p2 = this.anchor(b, a, shB);
ve.el.setAttribute('opacity', Math.min(a.alpha, b.alpha).toFixed(3));
if (e.lane) {
// offset perpendicular for two-lane (doubly) edges
const dx = p2.x - p1.x, dy = p2.y - p1.y, d = Math.hypot(dx, dy) || 1;
const ox = -dy / d * 7, oy = dx / d * 7;
p1 = { x: p1.x + ox, y: p1.y + oy }; p2 = { x: p2.x + ox, y: p2.y + oy };
ve.el.setAttribute('d', `M${p1.x} ${p1.y} L${p2.x} ${p2.y}`);
return;
}
if (e.kind === 'arc') {
// long wrap-around link: bow it away from the centroid
const mx = (p1.x + p2.x) / 2, my = (p1.y + p2.y) / 2;
const dx = p2.x - p1.x, dy = p2.y - p1.y, d = Math.hypot(dx, dy) || 1;
const bow = e.bow || 60;
const cx = mx - dy / d * bow, cy = my + dx / d * bow;
ve.el.setAttribute('d', `M${p1.x} ${p1.y} Q${cx} ${cy} ${p2.x} ${p2.y}`);
return;
}
ve.el.setAttribute('d', `M${p1.x} ${p1.y} L${p2.x} ${p2.y}`);
}
drawPtrs() {
this.gPtrs.innerHTML = '';
const groups = new Map(); // nodeId+side -> [labels]
const list = [...(this.sceneMeta.ptrs || [])];
if (this.curId && this.nodes.has(this.curId)) list.push({ name: 'cur', at: this.curId, side: 's', cur: true });
for (const p of list) {
const key = p.at + '|' + (p.side || 'n');
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(p);
}
for (const [key, ps] of groups) {
const [id, side] = key.split('|');
const vn = this.nodes.get(id);
if (!vn) continue;
const up = side === 'n';
const isCirc = ps[0].shape === 'circ';
const base = isCirc ? 24 : 21;
ps.forEach((p, i) => {
const g = document.createElementNS(SVGNS, 'g');
g.setAttribute('class', 'ptr ' + (p.cur ? 'pcur' : 'pbadge'));
const gap = 16, y0 = up ? vn.y - base - 8 : vn.y + base + 8;
const ty = up ? y0 - i * gap - 6 : y0 + i * gap + 8;
const ly1 = up ? vn.y - base : vn.y + base;
const ly2 = up ? y0 - i * gap : y0 + i * gap;
g.innerHTML = `<line x1="${vn.x}" y1="${ly1}" x2="${vn.x}" y2="${ly2}"></line><text x="${vn.x}" y="${ty}">${p.name}</text>`;
g.setAttribute('opacity', vn.alpha.toFixed(3));
this.gPtrs.appendChild(g);
});
}
}
}
/* ---------------- Player ---------------- */
class Player {
constructor(renderer) { this.R = renderer; this.busy = false; this.skip = false; }
speedMult() { return Number($('#speed').value) / 10; }
delay(ms) {
if (this.skip) return Promise.resolve();
return new Promise(res => setTimeout(res, ms / this.speedMult()));
}
logEntry(step, text, done) {
const body = $('#logbody');
const div = document.createElement('div');
div.className = 'lentry' + (done ? ' ldone' : '');
const num = document.createElement('span');
num.className = 'lstep'; num.textContent = step;
const p = document.createElement('p'); p.innerHTML = text;
div.appendChild(num); div.appendChild(p);
body.appendChild(div);
while (body.children.length > 90) body.removeChild(body.firstChild);
body.scrollTop = body.scrollHeight;
}
async play(steps, ctx) {
this.busy = true; this.skip = false;
document.body.classList.add('busy');
setOpsEnabled(false);
try {
const msg = $('#msg'), cnt = $('#count');
$('#logbody').innerHTML = '';
for (const s of steps) {
cnt.textContent = 'steps: ' + s.count;
if (s.t === 'note') { msg.innerHTML = s.text; this.logEntry(s.count, s.text); await this.delay(420); }
else if (s.t === 'cur') { this.R.setCur(s.id); await this.delay(400); }
else if (s.t === 'scene') { this.R.applyScene(s.scene, this.skip); await this.delay(s.slow ? 700 : 520); }
else if (s.t === 'done') {
this.R.setCur(null);
const line = s.text + (ctx ? ' · ' + ctx : '');
msg.innerHTML = '<b>' + line + '</b>';
this.logEntry(s.count, line, true);
}
}
} catch (err) {
console.error(err);
} finally {
// the player must always release the controls, whatever happened mid-run
this.R.setCur(null);
this.busy = false; this.skip = false;
document.body.classList.remove('busy');
setOpsEnabled(true);
}
}
}
'use strict';
/* ============ Linear structures: lists, stack, queue, rings ============ */
function mkNode(v) { return { id: nid(), v, next: null, prev: null, staged: false }; }
function sceneBounds(nodes, extra) {
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
for (const n of nodes) { x0 = Math.min(x0, n.x); y0 = Math.min(y0, n.y); x1 = Math.max(x1, n.x); y1 = Math.max(y1, n.y); }
for (const f of extra || []) {
x0 = Math.min(x0, f.x); y0 = Math.min(y0, f.y);
x1 = Math.max(x1, f.x + (f.w || 0)); y1 = Math.max(y1, f.y + (f.h || 0));
}
if (!isFinite(x0)) { x0 = 0; y0 = 0; x1 = 400; y1 = 200; }
return { x0, y0, w: x1 - x0, h: y1 - y0 };
}
/* ---------------- Singly linked list ---------------- */
class SinglyList extends Struct {
constructor() { super(); this.head = null; this.tail = null; this.n = 0; this.staged = null; this.stagedAt = 0; }
static label = 'Linked List';
max = 12;
bigo() { return [['search', `O(n) — up to ${this.n} steps now`], ['add head/tail', 'O(1)'], ['del tail', `O(n) — up to ${this.n} steps`]]; }
toArray() { const a = []; let c = this.head; while (c) { a.push(c); c = c.next; } return a; }
scene() {
const arr = this.toArray(); const gap = 96;
const ns = arr.map((nd, i) => ({ id: nd.id, v: nd.v, shape: 'rect', x: i * gap, y: 0, cls: this.nodeCls(nd.id) }));
if (this.staged) ns.push({ id: this.staged.id, v: this.staged.v, shape: 'rect', x: this.stagedAt * gap - 48, y: -100, cls: this.nodeCls(this.staged.id) });
const edges = [];
const all = this.staged ? arr.concat([this.staged]) : arr;
for (const nd of all) if (nd.next) edges.push({ from: nd.id, to: nd.next.id, cls: this.edgeCls(nd.id, nd.next.id) });
for (const k of this.fx.dying) { const [f, t] = k.split('>'); if (!edges.some(e => e.from === f && e.to === t)) edges.push({ from: f, to: t, cls: 'dying' }); }
const ptrs = [];
if (this.head) ptrs.push({ name: 'head', at: this.head.id, side: 'n' });
if (this.tail) ptrs.push({ name: 'tail', at: this.tail.id, side: 'n' });
const frames = arr.length || this.staged ? [] : [{ t: 'text', x: 200, y: 40, label: 'empty list — add a node', w: 0, h: 0 }];
const sc = { nodes: ns, edges, ptrs, frames, ...sceneBounds(ns, frames) };
if (!ns.length) { sc.x0 = 0; sc.y0 = 0; sc.w = 400; sc.h = 80; }
sc.y0 -= 40; sc.h += 60; // headroom for badges & staged lane
return sc;
}
full(R) { if (this.n >= this.max) { R.note(`Stage is full (max ${this.max} nodes) — delete some first.`); return true; } return false; }
stage(R, v, at, txt) {
this.staged = mkNode(v); this.stagedAt = at;
R.tick(); R.note(txt || `Create new node <b>${esc(v)}</b> <code>new = Node("${esc(v)}")</code>`); this.snapFx(R);
return this.staged;
}
land(node) { node.staged = false; this.staged = null; }
addHead(R, v) {
if (this.full(R)) return;
const nd = this.stage(R, v, 0);
if (this.head) {
nd.next = this.head; this.fx.fresh.add(nd.id + '>' + this.head.id);
R.tick(); R.note(`Point the new node at the old head <code>new.next = head</code> — <b>new → ${esc(this.head.v)}</b>`); this.snapFx(R);
}
this.land(nd); this.head = nd; if (!this.tail) this.tail = nd; this.n++;
R.tick(); R.note('Move the head pointer <code>head = new</code> — no traversal needed'); this.snapFx(R);
R.done('Add at head', 'O(1)');
}
addTail(R, v) {
if (this.full(R)) return;
if (!this.head) return this.addHead(R, v);
const nd = this.stage(R, v, this.n);
nd.prevLink = null;
this.tail.next = nd; this.fx.fresh.add(this.tail.id + '>' + nd.id);
R.tick(); R.note(`<b>tail</b> is already known — link it forward <code>tail.next = new</code> (no traversal)`); this.snapFx(R);
this.land(nd); this.tail = nd; this.n++;
R.tick(); R.note('Move the tail pointer <code>tail = new</code>'); this.snapFx(R);
R.done('Add at tail', 'O(1)');
}
walk(R, hops, from) {
let c = from || this.head;
R.cur(c.id); R.tick();
for (let i = 0; i < hops; i++) { c = c.next; R.tick(); R.cur(c.id); }
return c;
}
insertAt(R, v, i) {
if (this.full(R)) return;
if (i < 0 || i > this.n) { R.note(`Index ${i} is out of range 0…${this.n}.`); return; }
if (i === 0) return this.addHead(R, v);
if (i === this.n) { R.note(`Index ${i} = length → this is a tail insert.`); return this.addTail(R, v); }
R.note(`Traverse to index <b>${i - 1}</b>, the node before the slot <code>cur = cur.next</code> × ${i - 1}`);
const p = this.walk(R, i - 1);
const nd = this.stage(R, v, i, `Create new node <b>${esc(v)}</b> above the gap`);
nd.next = p.next; this.fx.fresh.add(nd.id + '>' + p.next.id);
R.tick(); R.note(`Link the new node into the chain <code>new.next = cur.next</code> — <b>new → ${esc(p.next.v)}</b>`); this.snapFx(R);
this.fx.dying.add(p.id + '>' + nd.next.id);
R.note(`The old link <b>${esc(p.v)} → ${esc(nd.next.v)}</b> is about to be cut — nothing may point past the new node`); this.snapFx(R);
p.next = nd; this.fx.fresh.add(p.id + '>' + nd.id);
this.land(nd); this.n++;
R.tick(); R.note(`Repoint the previous node <code>cur.next = new</code> — <b>${esc(p.v)} → ${esc(nd.v)}</b>. Two link writes total`); this.snapFx(R);
R.done(`Insert at ${i}`, 'O(n)');
}
delHead(R) {
if (!this.head) { R.note('List is empty.'); return; }
const h = this.head;
this.fx.doom.add(h.id);
if (h.next) this.fx.dying.add(h.id + '>' + h.next.id);
R.tick(); R.note(`Unlink <b>${esc(h.v)}</b>: step the head pointer over it <code>head = head.next</code>`); this.snapFx(R);
this.head = h.next; if (!this.head) this.tail = null; this.n--;
this.snapFx(R);
R.done('Delete at head', 'O(1)');
}
delTail(R) {
if (!this.head) { R.note('List is empty.'); return; }
if (this.n === 1) { R.note('Single node — it is both head and tail.'); return this.delHead(R); }
R.note('A singly list has no back-links, so we must walk to the node <i>before</i> tail <code>while (cur.next != tail)</code>');
const p = this.walk(R, this.n - 2);
this.fx.doom.add(this.tail.id); this.fx.dying.add(p.id + '>' + this.tail.id);
R.tick(); R.note(`Cut the last link <code>cur.next = null</code> — old tail <b>${esc(this.tail.v)}</b> is now unreachable`); this.snapFx(R);
p.next = null; this.tail = p; this.n--;
R.tick(); R.note('Move the tail pointer back <code>tail = cur</code>'); this.snapFx(R);
R.done('Delete at tail', 'O(n)');
}
delAt(R, i) {
if (i < 0 || i >= this.n) { R.note(`Index ${i} is out of range 0…${this.n - 1}.`); return; }
if (i === 0) return this.delHead(R);
if (i === this.n - 1) return this.delTail(R);
R.note(`Traverse to index <b>${i - 1}</b>`);
const p = this.walk(R, i - 1);
const vic = p.next;
this.fx.doom.add(vic.id); this.fx.dying.add(p.id + '>' + vic.id);
if (vic.next) this.fx.dying.add(vic.id + '>' + vic.next.id);
R.note(`Bypass <b>${esc(vic.v)}</b> with one write <code>prev.next = cur.next</code> — <b>${esc(p.v)} → ${esc(vic.next.v)}</b>; nothing points at <b>${esc(vic.v)}</b> anymore`); this.snapFx(R);
p.next = vic.next; this.fx.fresh.add(p.id + '>' + vic.next.id);
this.n--;
R.tick(); this.snapFx(R);
R.done(`Delete at ${i}`, 'O(n)');
}
delValue(R, v) {
if (!this.head) { R.note('List is empty.'); return; }
// one pass: keep a prev pointer while searching, unlink where we stand
let i = 0, c = this.head, p = null;
while (c) {
R.cur(c.id); R.tick();
if (cmp(c.v, v) === 0) {
R.note(`Found <b>${esc(v)}</b> at index ${i} — <b>prev</b> is already known, unlink in place`);
this.fx.doom.add(c.id);
if (p) this.fx.dying.add(p.id + '>' + c.id);
if (c.next) this.fx.dying.add(c.id + '>' + c.next.id);
this.snapFx(R);
if (!p) { this.head = c.next; R.note(`It was the head <code>head = head.next</code>`); }
else {
p.next = c.next;
if (c.next) { this.fx.fresh.add(p.id + '>' + c.next.id); R.note(`Bypass it <code>prev.next = cur.next</code>`); }
else R.note(`It was the tail <code>prev.next = null</code>`);
}
if (this.tail === c) this.tail = p;
if (!this.head) this.tail = null;
this.n--;
R.tick(); this.snapFx(R);
R.done('Delete value', 'O(n)'); return;
}
p = c; c = c.next; i++;
}
R.note(`<b>${esc(v)}</b> not found after ${R.count} steps.`); R.done('Delete value', 'O(n)');
}
editAt(R, v, i) {
if (i < 0 || i >= this.n) { R.note(`Index ${i} is out of range 0…${this.n - 1}.`); return; }
R.note(`Traverse to index <b>${i}</b> <code>cur = cur.next</code> × ${i}`);
const c = this.walk(R, i);
const old = c.v; c.v = v; this.fx.hit.add(c.id);
R.tick(); R.note(`Overwrite the value in place <code>cur.value = "${esc(v)}"</code> — <b>${esc(old)}</b> becomes <b>${esc(v)}</b>; no links change`); this.snapFx(R);
R.done(`Edit at ${i}`, 'O(n)');
}
search(R, v) {
let c = this.head, i = 0;
while (c) {
R.cur(c.id); R.tick();
if (cmp(c.v, v) === 0) {
this.fx.hit.add(c.id); R.note(`Found <b>${esc(v)}</b> at index ${i}`); this.snapFx(R);
R.done('Search', 'O(n)'); return;
}
c = c.next; i++;
}
R.note(`<b>${esc(v)}</b> is not in the list.`); R.done('Search', 'O(n)');
}
clear(R) {
if (!this.head) { R.note('Already empty.'); return; }
for (const nd of this.toArray()) this.fx.doom.add(nd.id);
R.tick(); R.note('Drop the entry pointers <code>head = null; tail = null</code> — every node becomes unreachable at once'); this.snapFx(R);
this.head = this.tail = null; this.n = 0;
this.snapFx(R);
R.done('Delete all', 'O(1)');
}
generate(R) {
this.head = this.tail = null; this.n = 0; this.staged = null;
const k = 5 + Math.floor(Math.random() * 3);
R.note(`Building ${k} random nodes at the tail…`);
for (let j = 0; j < k; j++) {
const nd = mkNode(randToken());
if (!this.head) { this.head = this.tail = nd; } else { this.tail.next = nd; this.tail = nd; }
this.n++; R.tick(); this.snapFx(R);
}
R.done('Generate', 'O(n)');
}
opDefs() {
return [
{ id: 'addHead', label: '+ Head', grp: 'add', val: 1, run: (R, v) => this.addHead(R, v) },
{ id: 'addTail', label: '+ Tail', grp: 'add', val: 1, run: (R, v) => this.addTail(R, v) },
{ id: 'insertAt', label: '+ At i', grp: 'add', val: 1, idx: 1, run: (R, v, i) => this.insertAt(R, v, i) },
{ id: 'delHead', label: 'Head', grp: 'del', danger: 1, run: R => this.delHead(R) },
{ id: 'delTail', label: 'Tail', grp: 'del', danger: 1, run: R => this.delTail(R) },
{ id: 'delAt', label: 'At i', grp: 'del', idx: 1, danger: 1, run: (R, v, i) => this.delAt(R, i) },
{ id: 'delVal', label: 'Value', grp: 'del', val: 1, danger: 1, run: (R, v) => this.delValue(R, v) },
{ id: 'clear', label: 'All', grp: 'del', danger: 1, run: R => this.clear(R) },
{ id: 'editAt', label: 'Edit at i', grp: 'etc', val: 1, idx: 1, run: (R, v, i) => this.editAt(R, v, i) },
{ id: 'search', label: 'Search', grp: 'etc', val: 1, run: (R, v) => this.search(R, v) },
{ id: 'gen', label: '🎲 Generate', grp: 'data', run: R => this.generate(R) },
];
}
}
/* ---------------- Doubly linked list ---------------- */
class DoublyList extends SinglyList {
static label = 'Doubly Linked';
bigo() { return [['search', `O(n) — up to ${this.n} now`], ['add/del head+tail', 'O(1)'], ['insert at', `O(n) — up to ${Math.ceil(this.n / 2)} from nearer end`]]; }
scene() {
const sc = super.scene();
const arr = this.toArray();
const all = this.staged ? arr.concat([this.staged]) : arr;
for (const nd of all) if (nd.prev && nd.prev.next === nd || nd.prev && nd.staged === false)
sc.edges.push({ from: nd.id, to: nd.prev.id, lane: 'prev', cls: this.edgeCls(nd.id, nd.prev.id) });
return sc;
}
addHead(R, v) {
if (this.full(R)) return;
const nd = this.stage(R, v, 0);
if (this.head) {
nd.next = this.head; this.head.prev = nd;
this.fx.fresh.add(nd.id + '>' + this.head.id); this.fx.fresh.add(this.head.id + '>' + nd.id);
R.tick(2); R.note(`Wire both directions <code>new.next = head; head.prev = new</code> — 2 link writes`); this.snapFx(R);
}
this.land(nd); this.head = nd; if (!this.tail) this.tail = nd; this.n++;
R.tick(); R.note('Move the head pointer <code>head = new</code>'); this.snapFx(R);
R.done('Add at head', 'O(1)');
}
addTail(R, v) {
if (this.full(R)) return;
if (!this.head) return this.addHead(R, v);
const nd = this.stage(R, v, this.n);
nd.prev = this.tail; this.tail.next = nd;
this.fx.fresh.add(this.tail.id + '>' + nd.id); this.fx.fresh.add(nd.id + '>' + this.tail.id);
R.tick(2); R.note(`Wire both directions at the tail <code>tail.next = new; new.prev = tail</code> — no traversal`); this.snapFx(R);
this.land(nd); this.tail = nd; this.n++;
R.tick(); R.note('Move the tail pointer <code>tail = new</code>'); this.snapFx(R);
R.done('Add at tail', 'O(1)');
}
walkFromTail(R, hopsBack) {
let c = this.tail;
R.cur(c.id); R.tick();
for (let i = 0; i < hopsBack; i++) { c = c.prev; R.tick(); R.cur(c.id); }
return c;
}
insertAt(R, v, i) {
if (this.full(R)) return;
if (i < 0 || i > this.n) { R.note(`Index ${i} is out of range 0…${this.n}.`); return; }
if (i === 0) return this.addHead(R, v);
if (i === this.n) { R.note(`Index ${i} = length → tail insert.`); return this.addTail(R, v); }
let p;
if (i - 1 <= this.n - 1 - i) {
R.note(`Index ${i} is in the first half → traverse forward from <b>head</b>`);
p = this.walk(R, i - 1);
} else {
R.note(`Index ${i} is in the second half → traverse backward from <b>tail</b> via <b>prev</b>`);
p = this.walkFromTail(R, this.n - i);
}
const nd = this.stage(R, v, i);
const q = p.next;
this.fx.dying.add(p.id + '>' + q.id); this.fx.dying.add(q.id + '>' + p.id);
R.note(`Cut both old links between <b>${esc(p.v)}</b> and <b>${esc(q.v)}</b> — the gap is open in both directions`); this.snapFx(R);
nd.next = q; nd.prev = p; p.next = nd; q.prev = nd;
this.fx.fresh.add(p.id + '>' + nd.id); this.fx.fresh.add(nd.id + '>' + q.id);
this.fx.fresh.add(nd.id + '>' + p.id); this.fx.fresh.add(q.id + '>' + nd.id);
this.land(nd); this.n++;
R.tick(4); R.note('Wire 4 new links <code>new.prev = before; new.next = after; before.next = new; after.prev = new</code>'); this.snapFx(R);
R.done(`Insert at ${i}`, 'O(n)');
}
delHead(R) {
if (!this.head) { R.note('List is empty.'); return; }
const h = this.head;
this.fx.doom.add(h.id);
if (h.next) { this.fx.dying.add(h.id + '>' + h.next.id); this.fx.dying.add(h.next.id + '>' + h.id); }
R.tick(); R.note(`Unlink head <b>${esc(h.v)}</b>; clear <b>${h.next ? esc(h.next.v) + '.prev' : 'tail'}</b>`); this.snapFx(R);
this.head = h.next; if (this.head) this.head.prev = null; else this.tail = null; this.n--;
R.tick(); this.snapFx(R);
R.done('Delete at head', 'O(1)');
}
delTail(R) {
if (!this.tail) { R.note('List is empty.'); return; }
if (this.n === 1) return this.delHead(R);
const t = this.tail;
this.fx.doom.add(t.id);
this.fx.dying.add(t.prev.id + '>' + t.id); this.fx.dying.add(t.id + '>' + t.prev.id);
R.note(`<b>tail.prev</b> is known — no traversal. Cut both links to <b>${esc(t.v)}</b>`); this.snapFx(R);
this.tail = t.prev; this.tail.next = null; this.n--;
R.tick(2); R.note('Step the tail back <code>tail = tail.prev; tail.next = null</code>'); this.snapFx(R);
R.done('Delete at tail', 'O(1)');
}
delAt(R, i) {
if (i < 0 || i >= this.n) { R.note(`Index ${i} is out of range 0…${this.n - 1}.`); return; }
if (i === 0) return this.delHead(R);
if (i === this.n - 1) return this.delTail(R);
let vic;
if (i <= this.n - 1 - i) { R.note(`Traverse forward to index <b>${i}</b>`); vic = this.walk(R, i); }
else { R.note(`Traverse backward to index <b>${i}</b>`); vic = this.walkFromTail(R, this.n - 1 - i); }
this.fx.doom.add(vic.id);
this.fx.dying.add(vic.prev.id + '>' + vic.id); this.fx.dying.add(vic.id + '>' + vic.prev.id);
this.fx.dying.add(vic.id + '>' + vic.next.id); this.fx.dying.add(vic.next.id + '>' + vic.id);
R.note(`Bypass <b>${esc(vic.v)}</b> in both directions <code>prev.next = cur.next; next.prev = cur.prev</code>`); this.snapFx(R);
vic.prev.next = vic.next; vic.next.prev = vic.prev;
this.fx.fresh.add(vic.prev.id + '>' + vic.next.id); this.fx.fresh.add(vic.next.id + '>' + vic.prev.id);
this.n--;
R.tick(2); this.snapFx(R);
R.done(`Delete at ${i}`, 'O(n)');
}
delValue(R, v) {
if (!this.head) { R.note('List is empty.'); return; }
let i = 0, c = this.head;
while (c) {
R.cur(c.id); R.tick();
if (cmp(c.v, v) === 0) {
R.note(`Found <b>${esc(v)}</b> at index ${i} — unlink in both directions, right here`);
this.fx.doom.add(c.id);
if (c.prev) { this.fx.dying.add(c.prev.id + '>' + c.id); this.fx.dying.add(c.id + '>' + c.prev.id); }
if (c.next) { this.fx.dying.add(c.id + '>' + c.next.id); this.fx.dying.add(c.next.id + '>' + c.id); }
this.snapFx(R);
if (c.prev) c.prev.next = c.next; else this.head = c.next;
if (c.next) c.next.prev = c.prev; else this.tail = c.prev;
if (c.prev && c.next) {
this.fx.fresh.add(c.prev.id + '>' + c.next.id); this.fx.fresh.add(c.next.id + '>' + c.prev.id);
}
this.n--;
R.tick(2); R.note(`<code>prev.next = cur.next; next.prev = cur.prev</code>`); this.snapFx(R);
R.done('Delete value', 'O(n)'); return;
}
c = c.next; i++;
}
R.note(`<b>${esc(v)}</b> not found after ${R.count} steps.`); R.done('Delete value', 'O(n)');
}
generate(R) {
this.head = this.tail = null; this.n = 0; this.staged = null;
const k = 5 + Math.floor(Math.random() * 3);
R.note(`Building ${k} random nodes…`);
for (let j = 0; j < k; j++) {
const nd = mkNode(randToken());
if (!this.head) this.head = this.tail = nd;
else { nd.prev = this.tail; this.tail.next = nd; this.tail = nd; }
this.n++; R.tick(); this.snapFx(R);
}
R.done('Generate', 'O(n)');
}
}
'use strict';
/* ============ Stack, Queue, Circular rings ============ */
class StackLIFO extends SinglyList {
static label = 'Stack · LIFO';
max = 9;
bigo() { return [['push / pop / peek', 'O(1)'], ['search', `O(n) — up to ${this.n} now`]]; }
scene() {
const arr = this.toArray(); const gap = 54;
const ns = arr.map((nd, i) => ({ id: nd.id, v: nd.v, shape: 'rect', x: 0, y: i * gap, cls: this.nodeCls(nd.id) }));
if (this.staged) ns.push({ id: this.staged.id, v: this.staged.v, shape: 'rect', x: -140, y: 0, cls: this.nodeCls(this.staged.id) });
const edges = [];
const all = this.staged ? arr.concat([this.staged]) : arr;
for (const nd of all) if (nd.next) edges.push({ from: nd.id, to: nd.next.id, cls: this.edgeCls(nd.id, nd.next.id) });
for (const k of this.fx.dying) { const [f, t] = k.split('>'); if (!edges.some(e => e.from === f && e.to === t)) edges.push({ from: f, to: t, cls: 'dying' }); }
const ptrs = this.head ? [{ name: 'top', at: this.head.id, side: 'n' }] : [];
const frames = ns.length ? [] : [{ t: 'text', x: 0, y: 40, label: 'empty stack — push a value', w: 0, h: 0 }];
const sc = { nodes: ns, edges, ptrs, frames, ...sceneBounds(ns, frames) };
if (!ns.length) { sc.x0 = -200; sc.y0 = 0; sc.w = 400; sc.h = 80; }
sc.y0 -= 42; sc.h += 62; sc.x0 -= 60; sc.w += 120;
return sc;
}
push(R, v) {
if (this.full(R)) return;
const nd = this.stage(R, v, 0, `Create node <b>${esc(v)}</b> — LIFO: last in, first out`);
if (this.head) {
nd.next = this.head; this.fx.fresh.add(nd.id + '>' + this.head.id);
R.tick(); R.note(`Stack the new node on the pile <code>new.next = top</code> — <b>new → ${esc(this.head.v)}</b>`); this.snapFx(R);
}
this.land(nd); this.head = nd; if (!this.tail) this.tail = nd; this.n++;
R.tick(); R.note('Move the top pointer <code>top = new</code> — the stack only ever touches its top'); this.snapFx(R);
R.done('Push', 'O(1)');
}
pop(R) {
if (!this.head) { R.note('Stack is empty — nothing to pop.'); return; }
const h = this.head;
this.fx.doom.add(h.id);
if (h.next) this.fx.dying.add(h.id + '>' + h.next.id);
R.tick(); R.note(`Pop <b>${esc(h.v)}</b> <code>top = top.next</code> — last in, first out`); this.snapFx(R);
this.head = h.next; if (!this.head) this.tail = null; this.n--;
R.tick(); this.snapFx(R);
R.done('Pop', 'O(1)');
}
peek(R) {
if (!this.head) { R.note('Stack is empty.'); return; }
this.fx.hit.add(this.head.id);
R.tick(); R.note(`Peek: <b>top</b> holds <b>${esc(this.head.v)}</b> — read without removing`); this.snapFx(R);
R.done('Peek', 'O(1)');
}
generate(R) {
this.head = this.tail = null; this.n = 0; this.staged = null;
const k = 4 + Math.floor(Math.random() * 3);
R.note(`Pushing ${k} random values…`);
for (let j = 0; j < k; j++) {
const nd = mkNode(randToken());
nd.next = this.head; this.head = nd; if (!this.tail) this.tail = nd;
this.n++; R.tick(); this.snapFx(R);
}
R.done('Generate', 'O(n)');
}
opDefs() {
return [
{ id: 'push', label: 'Push', grp: 'add', val: 1, run: (R, v) => this.push(R, v) },
{ id: 'pop', label: 'Pop', grp: 'del', danger: 1, run: R => this.pop(R) },
{ id: 'clear', label: 'All', grp: 'del', danger: 1, run: R => this.clear(R) },
{ id: 'peek', label: 'Peek', grp: 'etc', run: R => this.peek(R) },
{ id: 'search', label: 'Search', grp: 'etc', val: 1, run: (R, v) => this.search(R, v) },
{ id: 'gen', label: '🎲 Generate', grp: 'data', run: R => this.generate(R) },
];
}
}
class QueueFIFO extends SinglyList {
static label = 'Queue · FIFO';
bigo() { return [['enqueue / dequeue', 'O(1)'], ['search', `O(n) — up to ${this.n} now`]]; }
scene() {
const sc = super.scene();
sc.ptrs = [];
if (this.head) sc.ptrs.push({ name: 'front', at: this.head.id, side: 'n' });
if (this.tail) sc.ptrs.push({ name: 'rear', at: this.tail.id, side: 'n' });
return sc;
}
enqueue(R, v) {
if (this.full(R)) return;
if (!this.head) {
const nd = this.stage(R, v, 0, `Create node <b>${esc(v)}</b> — queue is empty, it becomes front and rear`);
this.land(nd); this.head = this.tail = nd; this.n++;
R.tick(); this.snapFx(R); R.done('Enqueue', 'O(1)'); return;
}
const nd = this.stage(R, v, this.n, `Create node <b>${esc(v)}</b> — FIFO: join at the <b>rear</b>`);
this.tail.next = nd; this.fx.fresh.add(this.tail.id + '>' + nd.id);
R.tick(); R.note('Link it behind the last rider <code>rear.next = new</code>'); this.snapFx(R);
this.land(nd); this.tail = nd; this.n++;
R.tick(); R.note('Move the rear pointer <code>rear = new</code>'); this.snapFx(R);
R.done('Enqueue', 'O(1)');
}
dequeue(R) {
if (!this.head) { R.note('Queue is empty — nothing to dequeue.'); return; }
const h = this.head;
this.fx.doom.add(h.id);
if (h.next) this.fx.dying.add(h.id + '>' + h.next.id);
R.tick(); R.note(`Dequeue <b>${esc(h.v)}</b> <code>front = front.next</code> — first in, first out`); this.snapFx(R);
this.head = h.next; if (!this.head) this.tail = null; this.n--;
R.tick(); this.snapFx(R);
R.done('Dequeue', 'O(1)');
}
peek(R) {
if (!this.head) { R.note('Queue is empty.'); return; }
this.fx.hit.add(this.head.id);
R.tick(); R.note(`Peek: <b>front</b> holds <b>${esc(this.head.v)}</b> — read without removing`); this.snapFx(R);
R.done('Peek', 'O(1)');
}
opDefs() {
return [
{ id: 'enq', label: 'Enqueue', grp: 'add', val: 1, run: (R, v) => this.enqueue(R, v) },
{ id: 'deq', label: 'Dequeue', grp: 'del', danger: 1, run: R => this.dequeue(R) },
{ id: 'clear', label: 'All', grp: 'del', danger: 1, run: R => this.clear(R) },
{ id: 'peek', label: 'Peek', grp: 'etc', run: R => this.peek(R) },
{ id: 'search', label: 'Search', grp: 'etc', val: 1, run: (R, v) => this.search(R, v) },
{ id: 'gen', label: '🎲 Generate', grp: 'data', run: R => this.generate(R) },
];
}
}
/* ---------------- Circular ring base (ellipse layout) ---------------- */
class RingBase extends SinglyList {
max = 10;
ringScene(doubly) {
const arr = this.toArray(); // toArray must terminate on rings — overridden below
const n = arr.length;
const rx = Math.max(150, n * 34), ry = rx * 0.52;
const ns = arr.map((nd, i) => {
const a = -Math.PI / 2 + (i / Math.max(n, 1)) * Math.PI * 2;
return { id: nd.id, v: nd.v, shape: 'rect', x: Math.cos(a) * rx, y: Math.sin(a) * ry, cls: this.nodeCls(nd.id) };
});
if (this.staged) ns.push({ id: this.staged.id, v: this.staged.v, shape: 'rect', x: 0, y: 0, cls: this.nodeCls(this.staged.id) });
const edges = [];