-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlinked-lists.html
More file actions
1415 lines (1228 loc) · 70.1 KB
/
linked-lists.html
File metadata and controls
1415 lines (1228 loc) · 70.1 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Linked Lists - Learn DSA - Better Dev</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
<body>
<header class="topbar">
<button class="sidebar-toggle" aria-label="Open navigation" aria-expanded="false">
<span class="hamburger-icon"></span>
</button>
<a href="index.html" class="logo">Better Dev</a>
</header>
<div class="sidebar-backdrop" aria-hidden="true"></div>
<aside class="sidebar" aria-label="Site navigation">
<div class="sidebar-header">
<span class="sidebar-title">Navigation</span>
<button class="sidebar-close" aria-label="Close navigation">×</button>
</div>
<div class="sidebar-search">
<input type="text" class="sidebar-search-input" placeholder="Search topics..." aria-label="Search topics">
<div class="sidebar-search-results"></div>
</div>
<nav class="sidebar-nav">
<div class="sidebar-group">
<a href="index.html">Home</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Mathematics</div>
<a href="pre-algebra.html">Pre-Algebra</a>
<a href="algebra.html">Algebra</a>
<a href="sequences-series.html">Sequences & Series</a>
<a href="geometry.html">Geometry</a>
<a href="calculus.html">Calculus</a>
<a href="discrete-math.html">Discrete Math</a>
<a href="linear-algebra.html">Linear Algebra</a>
<a href="probability.html">Probability & Statistics</a>
<a href="binary-systems.html">Binary & Number Systems</a>
<a href="number-theory.html">Number Theory for CP</a>
<a href="computational-geometry.html">Computational Geometry</a>
<a href="game-theory.html">Game Theory</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Data Structures & Algorithms</div>
<a href="dsa-foundations.html">DSA Foundations</a>
<a href="arrays.html">Arrays & Strings</a>
<a href="stacks-queues.html">Stacks & Queues</a>
<a href="hashmaps.html">Hash Maps & Sets</a>
<a href="linked-lists.html">Linked Lists</a>
<a href="trees.html">Trees & BST</a>
<a href="graphs.html">Graphs</a>
<a href="sorting.html">Sorting & Searching</a>
<a href="patterns.html">LeetCode Patterns</a>
<a href="dp.html">Dynamic Programming</a>
<a href="advanced.html">Advanced Topics</a>
<a href="string-algorithms.html">String Algorithms</a>
<a href="advanced-graphs.html">Advanced Graphs</a>
<a href="advanced-dp.html">Advanced DP</a>
<a href="advanced-ds.html">Advanced Data Structures</a>
<a href="leetcode-650.html">The 650 Problems</a>
<a href="competitive-programming.html">CP Roadmap</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Languages & Systems</div>
<a href="cpp.html">C++</a>
<a href="golang.html">Go</a>
<a href="javascript.html">JavaScript Deep Dive</a>
<a href="typescript.html">TypeScript</a>
<a href="nodejs.html">Node.js Internals</a>
<a href="os.html">Operating Systems</a>
<a href="linux.html">Linux</a>
<a href="git.html">Git</a>
<a href="backend.html">Backend</a>
<a href="system-design.html">System Design</a>
<a href="networking.html">Networking</a>
<a href="cloud.html">Cloud & Infrastructure</a>
<a href="docker.html">Docker & Compose</a>
<a href="kubernetes.html">Kubernetes</a>
<a href="message-queues.html">Queues & Pub/Sub</a>
<a href="selfhosting.html">VPS & Self-Hosting</a>
<a href="databases.html">PostgreSQL & MySQL</a>
<a href="stripe.html">Stripe & Payments</a>
<a href="distributed-systems.html">Distributed Systems</a>
<a href="backend-engineering.html">Backend Engineering</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">JS/TS Ecosystem</div>
<a href="js-tooling.html">Tooling & Bundlers</a>
<a href="js-testing.html">Testing</a>
<a href="ts-projects.html">Building with TS</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">More</div>
<a href="seans-brain.html">Sean's Brain</a>
</div>
</nav>
</aside>
<div class="container">
<!-- PAGE HEADER -->
<div class="page-header">
<div class="breadcrumb"><a href="index.html">Home</a> / Linked Lists</div>
<h1>Linked Lists</h1>
<p>Nodes connected by pointers -- the fundamental dynamic data structure for efficient insertions and deletions.</p>
</div>
<!-- TABLE OF CONTENTS -->
<div class="toc">
<h4>Table of Contents</h4>
<a href="#what-is">1. What is a Linked List?</a>
<a href="#singly-vs-doubly">2. Singly vs Doubly Linked List</a>
<a href="#complexity">3. Time Complexity</a>
<a href="#implementation">4. Implementation from Scratch</a>
<a href="#techniques">5. Common Linked List Techniques</a>
<a href="#leetcode">6. LeetCode Problems</a>
<a href="#when-to-use">7. When to Use Linked Lists</a>
<a href="#quiz">8. Practice Quiz</a>
</div>
<!-- ======================= SECTION 1 ======================= -->
<section id="what-is">
<h2>1. What is a Linked List?</h2>
<p>A <strong>linked list</strong> is a linear data structure where each element (called a <strong>node</strong>) contains two things: the data itself and a <strong>pointer</strong> (reference) to the next node in the sequence. Unlike arrays, linked list nodes are <strong>not stored contiguously</strong> in memory -- they can be scattered anywhere in the heap.</p>
<h3>Node Structure</h3>
<p>Each node holds:</p>
<ul>
<li><strong>Data</strong> -- the value stored in the node</li>
<li><strong>Next pointer</strong> -- a reference to the next node (or <code>null</code> if it is the last node)</li>
</ul>
<h3>Visual Representation</h3>
<div class="formula-box">
Head Tail<br>
| |<br>
v v<br>
[1 | next] ---> [2 | next] ---> [3 | next] ---> null
</div>
<p>The <strong>head</strong> pointer always references the first node. The <strong>tail</strong> is the last node whose <code>next</code> pointer is <code>null</code>. Some implementations also maintain an explicit tail pointer for O(1) append operations.</p>
<div class="tip-box">
<div class="label">Key Insight</div>
<p>Arrays give you O(1) random access because elements sit next to each other in memory. Linked lists sacrifice random access (O(n) to reach index i) but gain O(1) insertions/deletions at the head -- no shifting elements required.</p>
</div>
<h3>Memory Layout: Array vs Linked List</h3>
<div class="formula-box">
<strong>Array (contiguous):</strong><br>
Memory: | 1 | 2 | 3 | 4 | 5 |<br>
Index: 0 1 2 3 4<br><br>
<strong>Linked List (scattered):</strong><br>
Addr 0x100: [1 | 0x348]<br>
Addr 0x348: [2 | 0x0F0]<br>
Addr 0x0F0: [3 | 0x7A2]<br>
Addr 0x7A2: [4 | null]
</div>
</section>
<!-- ======================= SECTION 2 ======================= -->
<section id="singly-vs-doubly">
<h2>2. Singly vs Doubly Linked List</h2>
<h3>Singly Linked List</h3>
<p>Each node stores data and a <strong>single pointer</strong> to the next node. Traversal is one-directional -- you can only go forward.</p>
<div class="formula-box">
Head<br>
|<br>
v<br>
[A | ->] ---> [B | ->] ---> [C | ->] ---> null
</div>
<h3>Doubly Linked List</h3>
<p>Each node stores data, a pointer to the <strong>next</strong> node, and a pointer to the <strong>previous</strong> node. Traversal goes both directions.</p>
<div class="formula-box">
Head Tail<br>
| |<br>
v v<br>
null <--- [prev | A | next] <---> [prev | B | next] <---> [prev | C | next] ---> null
</div>
<h3>Trade-offs</h3>
<table>
<thead>
<tr>
<th>Aspect</th>
<th>Singly Linked List</th>
<th>Doubly Linked List</th>
</tr>
</thead>
<tbody>
<tr>
<td>Memory per node</td>
<td>Less (1 pointer)</td>
<td>More (2 pointers)</td>
</tr>
<tr>
<td>Forward traversal</td>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr>
<td>Backward traversal</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>Delete given node</td>
<td>O(n) -- need predecessor</td>
<td>O(1) -- has prev pointer</td>
</tr>
<tr>
<td>Insert before node</td>
<td>O(n) -- need predecessor</td>
<td>O(1) -- has prev pointer</td>
</tr>
<tr>
<td>Implementation</td>
<td>Simpler</td>
<td>More complex</td>
</tr>
<tr>
<td>Use case</td>
<td>Stacks, simple lists</td>
<td>LRU cache, browser history</td>
</tr>
</tbody>
</table>
</section>
<!-- ======================= SECTION 3 ======================= -->
<section id="complexity">
<h2>3. Time Complexity</h2>
<table>
<thead>
<tr>
<th>Operation</th>
<th>Singly LL</th>
<th>Doubly LL</th>
<th>Array</th>
</tr>
</thead>
<tbody>
<tr>
<td>Access by index</td>
<td>O(n)</td>
<td>O(n)</td>
<td>O(1)</td>
</tr>
<tr>
<td>Insert at head</td>
<td>O(1)</td>
<td>O(1)</td>
<td>O(n)</td>
</tr>
<tr>
<td>Insert at tail</td>
<td>O(n) / O(1)*</td>
<td>O(1)</td>
<td>O(1) amortized</td>
</tr>
<tr>
<td>Insert at middle</td>
<td>O(n)</td>
<td>O(n)</td>
<td>O(n)</td>
</tr>
<tr>
<td>Delete head</td>
<td>O(1)</td>
<td>O(1)</td>
<td>O(n)</td>
</tr>
<tr>
<td>Delete tail</td>
<td>O(n)</td>
<td>O(1)</td>
<td>O(1)</td>
</tr>
<tr>
<td>Search</td>
<td>O(n)</td>
<td>O(n)</td>
<td>O(n)</td>
</tr>
</tbody>
</table>
<div class="tip-box">
<div class="label">Note</div>
<p>* Singly linked list insert at tail is O(1) <strong>only if you maintain a tail pointer</strong>. Without one, you must traverse the entire list to find the end, making it O(n).</p>
</div>
<div class="warning-box">
<div class="label">Cache Performance</div>
<p>Even though linked lists have great theoretical complexity for insertions/deletions, arrays often win in practice because of <strong>CPU cache locality</strong>. Array elements sit next to each other in memory, so the CPU can prefetch them efficiently. Linked list nodes are scattered in memory, causing frequent cache misses.</p>
</div>
<div class="warning-box">
<div class="label">Critical O(1) Qualifier</div>
<p>All linked list "O(1) insertion/deletion" claims assume <strong>you already hold a pointer to the node</strong>. Finding the node first is O(n). Without a pre-held pointer, insertion at position i is O(i), not O(1).</p>
<p><strong>Rule:</strong> If you need O(1) append, you MUST maintain a tail pointer. Without it, append is O(n).</p>
</div>
</section>
<!-- ======================= SECTION 4 ======================= -->
<section id="implementation">
<h2>4. Implementation from Scratch</h2>
<!-- --- SINGLY LINKED LIST --- -->
<h3>Singly Linked List</h3>
<p>We build a <code>Node</code> class (data + next pointer) and a <code>LinkedList</code> class with core operations: <strong>append</strong>, <strong>prepend</strong>, <strong>insert_at</strong>, <strong>delete</strong>, <strong>search</strong>, <strong>display</strong>, and <strong>length</strong>.</p>
<h3>Python -- Singly Linked List</h3>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">class</span> <span class="builtin">Node</span>:
<span class="keyword">def</span> <span class="function">__init__</span>(<span class="builtin">self</span>, data):
<span class="builtin">self</span>.data = data
<span class="builtin">self</span>.next = <span class="keyword">None</span>
<span class="keyword">class</span> <span class="builtin">LinkedList</span>:
<span class="keyword">def</span> <span class="function">__init__</span>(<span class="builtin">self</span>):
<span class="builtin">self</span>.head = <span class="keyword">None</span>
<span class="builtin">self</span>._length = <span class="number">0</span>
<span class="keyword">def</span> <span class="function">append</span>(<span class="builtin">self</span>, data):
<span class="comment">"""Add node to the end of the list."""</span>
new_node = <span class="builtin">Node</span>(data)
<span class="builtin">self</span>._length += <span class="number">1</span>
<span class="keyword">if not</span> <span class="builtin">self</span>.head:
<span class="builtin">self</span>.head = new_node
<span class="keyword">return</span>
current = <span class="builtin">self</span>.head
<span class="keyword">while</span> current.next:
current = current.next
current.next = new_node
<span class="keyword">def</span> <span class="function">prepend</span>(<span class="builtin">self</span>, data):
<span class="comment">"""Add node to the beginning of the list. O(1)."""</span>
new_node = <span class="builtin">Node</span>(data)
new_node.next = <span class="builtin">self</span>.head
<span class="builtin">self</span>.head = new_node
<span class="builtin">self</span>._length += <span class="number">1</span>
<span class="keyword">def</span> <span class="function">insert_at</span>(<span class="builtin">self</span>, index, data):
<span class="comment">"""Insert node at a specific index."""</span>
<span class="keyword">if</span> index < <span class="number">0</span> <span class="keyword">or</span> index > <span class="builtin">self</span>._length:
<span class="keyword">raise</span> <span class="builtin">IndexError</span>(<span class="string">"Index out of bounds"</span>)
<span class="keyword">if</span> index == <span class="number">0</span>:
<span class="builtin">self</span>.<span class="function">prepend</span>(data)
<span class="keyword">return</span>
new_node = <span class="builtin">Node</span>(data)
current = <span class="builtin">self</span>.head
<span class="keyword">for</span> _ <span class="keyword">in</span> <span class="builtin">range</span>(index - <span class="number">1</span>):
current = current.next
new_node.next = current.next
current.next = new_node
<span class="builtin">self</span>._length += <span class="number">1</span>
<span class="keyword">def</span> <span class="function">delete</span>(<span class="builtin">self</span>, data):
<span class="comment">"""Delete the first node with the given value."""</span>
<span class="keyword">if not</span> <span class="builtin">self</span>.head:
<span class="keyword">return</span>
<span class="keyword">if</span> <span class="builtin">self</span>.head.data == data:
<span class="builtin">self</span>.head = <span class="builtin">self</span>.head.next
<span class="builtin">self</span>._length -= <span class="number">1</span>
<span class="keyword">return</span>
current = <span class="builtin">self</span>.head
<span class="keyword">while</span> current.next:
<span class="keyword">if</span> current.next.data == data:
current.next = current.next.next
<span class="builtin">self</span>._length -= <span class="number">1</span>
<span class="keyword">return</span>
current = current.next
<span class="keyword">def</span> <span class="function">search</span>(<span class="builtin">self</span>, data):
<span class="comment">"""Return True if value exists in the list."""</span>
current = <span class="builtin">self</span>.head
<span class="keyword">while</span> current:
<span class="keyword">if</span> current.data == data:
<span class="keyword">return</span> <span class="keyword">True</span>
current = current.next
<span class="keyword">return</span> <span class="keyword">False</span>
<span class="keyword">def</span> <span class="function">display</span>(<span class="builtin">self</span>):
<span class="comment">"""Print the list as: 1 -> 2 -> 3 -> null"""</span>
parts = []
current = <span class="builtin">self</span>.head
<span class="keyword">while</span> current:
parts.<span class="function">append</span>(<span class="builtin">str</span>(current.data))
current = current.next
<span class="builtin">print</span>(<span class="string">" -> "</span>.<span class="function">join</span>(parts) + <span class="string">" -> null"</span>)
<span class="keyword">def</span> <span class="function">length</span>(<span class="builtin">self</span>):
<span class="comment">"""Return the number of nodes."""</span>
<span class="keyword">return</span> <span class="builtin">self</span>._length
<span class="comment"># Usage</span>
ll = <span class="builtin">LinkedList</span>()
ll.<span class="function">append</span>(<span class="number">1</span>)
ll.<span class="function">append</span>(<span class="number">2</span>)
ll.<span class="function">append</span>(<span class="number">3</span>)
ll.<span class="function">prepend</span>(<span class="number">0</span>)
ll.<span class="function">insert_at</span>(<span class="number">2</span>, <span class="number">99</span>)
ll.<span class="function">display</span>() <span class="comment"># 0 -> 1 -> 99 -> 2 -> 3 -> null</span>
ll.<span class="function">delete</span>(<span class="number">99</span>)
ll.<span class="function">display</span>() <span class="comment"># 0 -> 1 -> 2 -> 3 -> null</span>
<span class="builtin">print</span>(ll.<span class="function">search</span>(<span class="number">2</span>)) <span class="comment"># True</span>
<span class="builtin">print</span>(ll.<span class="function">length</span>()) <span class="comment"># 4</span></code></pre>
<div class="example-box">
<div class="label">Step-by-step: append(3)</div>
<p><strong>1.</strong> Create new node with data=3, next=null.<br>
<strong>2.</strong> If head is null, set head = new node. Done.<br>
<strong>3.</strong> Otherwise, start at head. Walk forward until you find a node whose next is null (the tail).<br>
<strong>4.</strong> Set that tail node's next to the new node. The new node becomes the new tail.</p>
</div>
<h3>JavaScript -- Singly Linked List</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">class</span> <span class="builtin">Node</span> {
<span class="function">constructor</span>(data) {
<span class="keyword">this</span>.data = data;
<span class="keyword">this</span>.next = <span class="keyword">null</span>;
}
}
<span class="keyword">class</span> <span class="builtin">LinkedList</span> {
<span class="function">constructor</span>() {
<span class="keyword">this</span>.head = <span class="keyword">null</span>;
<span class="keyword">this</span>._length = <span class="number">0</span>;
}
<span class="function">append</span>(data) {
<span class="keyword">const</span> newNode = <span class="keyword">new</span> <span class="builtin">Node</span>(data);
<span class="keyword">this</span>._length++;
<span class="keyword">if</span> (!<span class="keyword">this</span>.head) {
<span class="keyword">this</span>.head = newNode;
<span class="keyword">return</span>;
}
<span class="keyword">let</span> current = <span class="keyword">this</span>.head;
<span class="keyword">while</span> (current.next) {
current = current.next;
}
current.next = newNode;
}
<span class="function">prepend</span>(data) {
<span class="keyword">const</span> newNode = <span class="keyword">new</span> <span class="builtin">Node</span>(data);
newNode.next = <span class="keyword">this</span>.head;
<span class="keyword">this</span>.head = newNode;
<span class="keyword">this</span>._length++;
}
<span class="function">insertAt</span>(index, data) {
<span class="keyword">if</span> (index < <span class="number">0</span> || index > <span class="keyword">this</span>._length) {
<span class="keyword">throw new</span> <span class="builtin">Error</span>(<span class="string">"Index out of bounds"</span>);
}
<span class="keyword">if</span> (index === <span class="number">0</span>) {
<span class="keyword">this</span>.<span class="function">prepend</span>(data);
<span class="keyword">return</span>;
}
<span class="keyword">const</span> newNode = <span class="keyword">new</span> <span class="builtin">Node</span>(data);
<span class="keyword">let</span> current = <span class="keyword">this</span>.head;
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < index - <span class="number">1</span>; i++) {
current = current.next;
}
newNode.next = current.next;
current.next = newNode;
<span class="keyword">this</span>._length++;
}
<span class="function">delete</span>(data) {
<span class="keyword">if</span> (!<span class="keyword">this</span>.head) <span class="keyword">return</span>;
<span class="keyword">if</span> (<span class="keyword">this</span>.head.data === data) {
<span class="keyword">this</span>.head = <span class="keyword">this</span>.head.next;
<span class="keyword">this</span>._length--;
<span class="keyword">return</span>;
}
<span class="keyword">let</span> current = <span class="keyword">this</span>.head;
<span class="keyword">while</span> (current.next) {
<span class="keyword">if</span> (current.next.data === data) {
current.next = current.next.next;
<span class="keyword">this</span>._length--;
<span class="keyword">return</span>;
}
current = current.next;
}
}
<span class="function">search</span>(data) {
<span class="keyword">let</span> current = <span class="keyword">this</span>.head;
<span class="keyword">while</span> (current) {
<span class="keyword">if</span> (current.data === data) <span class="keyword">return true</span>;
current = current.next;
}
<span class="keyword">return false</span>;
}
<span class="function">display</span>() {
<span class="keyword">const</span> parts = [];
<span class="keyword">let</span> current = <span class="keyword">this</span>.head;
<span class="keyword">while</span> (current) {
parts.<span class="function">push</span>(current.data);
current = current.next;
}
<span class="builtin">console</span>.<span class="function">log</span>(parts.<span class="function">join</span>(<span class="string">" -> "</span>) + <span class="string">" -> null"</span>);
}
<span class="function">length</span>() {
<span class="keyword">return this</span>._length;
}
}
<span class="comment">// Usage</span>
<span class="keyword">const</span> ll = <span class="keyword">new</span> <span class="builtin">LinkedList</span>();
ll.<span class="function">append</span>(<span class="number">1</span>);
ll.<span class="function">append</span>(<span class="number">2</span>);
ll.<span class="function">append</span>(<span class="number">3</span>);
ll.<span class="function">prepend</span>(<span class="number">0</span>);
ll.<span class="function">insertAt</span>(<span class="number">2</span>, <span class="number">99</span>);
ll.<span class="function">display</span>(); <span class="comment">// 0 -> 1 -> 99 -> 2 -> 3 -> null</span>
ll.<span class="function">delete</span>(<span class="number">99</span>);
ll.<span class="function">display</span>(); <span class="comment">// 0 -> 1 -> 2 -> 3 -> null</span>
<span class="builtin">console</span>.<span class="function">log</span>(ll.<span class="function">search</span>(<span class="number">2</span>)); <span class="comment">// true</span>
<span class="builtin">console</span>.<span class="function">log</span>(ll.<span class="function">length</span>()); <span class="comment">// 4</span></code></pre>
<!-- --- DOUBLY LINKED LIST --- -->
<h3>Doubly Linked List</h3>
<p>The doubly linked list adds a <code>prev</code> pointer to each node. This enables O(1) deletion of a given node and backward traversal, at the cost of extra memory per node.</p>
<h3>Python -- Doubly Linked List</h3>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">class</span> <span class="builtin">DNode</span>:
<span class="keyword">def</span> <span class="function">__init__</span>(<span class="builtin">self</span>, data):
<span class="builtin">self</span>.data = data
<span class="builtin">self</span>.prev = <span class="keyword">None</span>
<span class="builtin">self</span>.next = <span class="keyword">None</span>
<span class="keyword">class</span> <span class="builtin">DoublyLinkedList</span>:
<span class="keyword">def</span> <span class="function">__init__</span>(<span class="builtin">self</span>):
<span class="builtin">self</span>.head = <span class="keyword">None</span>
<span class="builtin">self</span>.tail = <span class="keyword">None</span>
<span class="builtin">self</span>._length = <span class="number">0</span>
<span class="keyword">def</span> <span class="function">append</span>(<span class="builtin">self</span>, data):
<span class="comment">"""Add node to end. O(1) with tail pointer."""</span>
new_node = <span class="builtin">DNode</span>(data)
<span class="builtin">self</span>._length += <span class="number">1</span>
<span class="keyword">if not</span> <span class="builtin">self</span>.head:
<span class="builtin">self</span>.head = new_node
<span class="builtin">self</span>.tail = new_node
<span class="keyword">return</span>
new_node.prev = <span class="builtin">self</span>.tail
<span class="builtin">self</span>.tail.next = new_node
<span class="builtin">self</span>.tail = new_node
<span class="keyword">def</span> <span class="function">prepend</span>(<span class="builtin">self</span>, data):
<span class="comment">"""Add node to beginning. O(1)."""</span>
new_node = <span class="builtin">DNode</span>(data)
<span class="builtin">self</span>._length += <span class="number">1</span>
<span class="keyword">if not</span> <span class="builtin">self</span>.head:
<span class="builtin">self</span>.head = new_node
<span class="builtin">self</span>.tail = new_node
<span class="keyword">return</span>
new_node.next = <span class="builtin">self</span>.head
<span class="builtin">self</span>.head.prev = new_node
<span class="builtin">self</span>.head = new_node
<span class="keyword">def</span> <span class="function">delete_node</span>(<span class="builtin">self</span>, node):
<span class="comment">"""Delete a specific node reference. O(1)."""</span>
<span class="keyword">if</span> node.prev:
node.prev.next = node.next
<span class="keyword">else</span>:
<span class="builtin">self</span>.head = node.next
<span class="keyword">if</span> node.next:
node.next.prev = node.prev
<span class="keyword">else</span>:
<span class="builtin">self</span>.tail = node.prev
<span class="builtin">self</span>._length -= <span class="number">1</span>
<span class="keyword">def</span> <span class="function">delete_value</span>(<span class="builtin">self</span>, data):
<span class="comment">"""Delete first node with given value."""</span>
current = <span class="builtin">self</span>.head
<span class="keyword">while</span> current:
<span class="keyword">if</span> current.data == data:
<span class="builtin">self</span>.<span class="function">delete_node</span>(current)
<span class="keyword">return</span>
current = current.next
<span class="keyword">def</span> <span class="function">search</span>(<span class="builtin">self</span>, data):
<span class="comment">"""Return True if value exists."""</span>
current = <span class="builtin">self</span>.head
<span class="keyword">while</span> current:
<span class="keyword">if</span> current.data == data:
<span class="keyword">return</span> <span class="keyword">True</span>
current = current.next
<span class="keyword">return</span> <span class="keyword">False</span>
<span class="keyword">def</span> <span class="function">display_forward</span>(<span class="builtin">self</span>):
parts = []
current = <span class="builtin">self</span>.head
<span class="keyword">while</span> current:
parts.<span class="function">append</span>(<span class="builtin">str</span>(current.data))
current = current.next
<span class="builtin">print</span>(<span class="string">"null <-> "</span> + <span class="string">" <-> "</span>.<span class="function">join</span>(parts) + <span class="string">" <-> null"</span>)
<span class="keyword">def</span> <span class="function">display_backward</span>(<span class="builtin">self</span>):
parts = []
current = <span class="builtin">self</span>.tail
<span class="keyword">while</span> current:
parts.<span class="function">append</span>(<span class="builtin">str</span>(current.data))
current = current.prev
<span class="builtin">print</span>(<span class="string">"null <-> "</span> + <span class="string">" <-> "</span>.<span class="function">join</span>(parts) + <span class="string">" <-> null"</span>)
<span class="keyword">def</span> <span class="function">length</span>(<span class="builtin">self</span>):
<span class="keyword">return</span> <span class="builtin">self</span>._length</code></pre>
<h3>JavaScript -- Doubly Linked List</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">class</span> <span class="builtin">DNode</span> {
<span class="function">constructor</span>(data) {
<span class="keyword">this</span>.data = data;
<span class="keyword">this</span>.prev = <span class="keyword">null</span>;
<span class="keyword">this</span>.next = <span class="keyword">null</span>;
}
}
<span class="keyword">class</span> <span class="builtin">DoublyLinkedList</span> {
<span class="function">constructor</span>() {
<span class="keyword">this</span>.head = <span class="keyword">null</span>;
<span class="keyword">this</span>.tail = <span class="keyword">null</span>;
<span class="keyword">this</span>._length = <span class="number">0</span>;
}
<span class="function">append</span>(data) {
<span class="keyword">const</span> newNode = <span class="keyword">new</span> <span class="builtin">DNode</span>(data);
<span class="keyword">this</span>._length++;
<span class="keyword">if</span> (!<span class="keyword">this</span>.head) {
<span class="keyword">this</span>.head = newNode;
<span class="keyword">this</span>.tail = newNode;
<span class="keyword">return</span>;
}
newNode.prev = <span class="keyword">this</span>.tail;
<span class="keyword">this</span>.tail.next = newNode;
<span class="keyword">this</span>.tail = newNode;
}
<span class="function">prepend</span>(data) {
<span class="keyword">const</span> newNode = <span class="keyword">new</span> <span class="builtin">DNode</span>(data);
<span class="keyword">this</span>._length++;
<span class="keyword">if</span> (!<span class="keyword">this</span>.head) {
<span class="keyword">this</span>.head = newNode;
<span class="keyword">this</span>.tail = newNode;
<span class="keyword">return</span>;
}
newNode.next = <span class="keyword">this</span>.head;
<span class="keyword">this</span>.head.prev = newNode;
<span class="keyword">this</span>.head = newNode;
}
<span class="function">deleteNode</span>(node) {
<span class="keyword">if</span> (node.prev) {
node.prev.next = node.next;
} <span class="keyword">else</span> {
<span class="keyword">this</span>.head = node.next;
}
<span class="keyword">if</span> (node.next) {
node.next.prev = node.prev;
} <span class="keyword">else</span> {
<span class="keyword">this</span>.tail = node.prev;
}
<span class="keyword">this</span>._length--;
}
<span class="function">deleteValue</span>(data) {
<span class="keyword">let</span> current = <span class="keyword">this</span>.head;
<span class="keyword">while</span> (current) {
<span class="keyword">if</span> (current.data === data) {
<span class="keyword">this</span>.<span class="function">deleteNode</span>(current);
<span class="keyword">return</span>;
}
current = current.next;
}
}
<span class="function">search</span>(data) {
<span class="keyword">let</span> current = <span class="keyword">this</span>.head;
<span class="keyword">while</span> (current) {
<span class="keyword">if</span> (current.data === data) <span class="keyword">return true</span>;
current = current.next;
}
<span class="keyword">return false</span>;
}
<span class="function">displayForward</span>() {
<span class="keyword">const</span> parts = [];
<span class="keyword">let</span> current = <span class="keyword">this</span>.head;
<span class="keyword">while</span> (current) {
parts.<span class="function">push</span>(current.data);
current = current.next;
}
<span class="builtin">console</span>.<span class="function">log</span>(<span class="string">"null <-> "</span> + parts.<span class="function">join</span>(<span class="string">" <-> "</span>) + <span class="string">" <-> null"</span>);
}
<span class="function">displayBackward</span>() {
<span class="keyword">const</span> parts = [];
<span class="keyword">let</span> current = <span class="keyword">this</span>.tail;
<span class="keyword">while</span> (current) {
parts.<span class="function">push</span>(current.data);
current = current.prev;
}
<span class="builtin">console</span>.<span class="function">log</span>(<span class="string">"null <-> "</span> + parts.<span class="function">join</span>(<span class="string">" <-> "</span>) + <span class="string">" <-> null"</span>);
}
<span class="function">length</span>() {
<span class="keyword">return this</span>._length;
}
}</code></pre>
</section>
<!-- ======================= SECTION 5 ======================= -->
<section id="techniques">
<h2>5. Common Linked List Techniques</h2>
<!-- --- FAST AND SLOW POINTERS --- -->
<h3>Fast and Slow Pointers (Tortoise and Hare)</h3>
<p>This technique uses two pointers that move at different speeds through the list. The <strong>slow pointer</strong> moves one step at a time, while the <strong>fast pointer</strong> moves two steps. This pattern is used to detect cycles and find the middle of a linked list.</p>
<h3>Detect Cycle in a Linked List</h3>
<p>If a cycle exists, the fast pointer will eventually "lap" the slow pointer and they will meet. If no cycle exists, the fast pointer reaches <code>null</code>.</p>
<div class="formula-box">
1 -> 2 -> 3 -> 4 -> 5<br>
^ |<br>
|_________|<br>
<br>
slow: 1, 2, 3, 4, 5, 3, 4, ...<br>
fast: 1, 3, 5, 4, 3, 5, 4, ...<br>
They meet at node 4 (or 5 depending on start).
</div>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">has_cycle</span>(head):
<span class="comment">"""Floyd's cycle detection. O(n) time, O(1) space."""</span>
slow = head
fast = head
<span class="keyword">while</span> fast <span class="keyword">and</span> fast.next:
slow = slow.next <span class="comment"># Move 1 step</span>
fast = fast.next.next <span class="comment"># Move 2 steps</span>
<span class="keyword">if</span> slow == fast:
<span class="keyword">return</span> <span class="keyword">True</span> <span class="comment"># Cycle detected</span>
<span class="keyword">return</span> <span class="keyword">False</span> <span class="comment"># No cycle</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">hasCycle</span>(head) {
<span class="keyword">let</span> slow = head;
<span class="keyword">let</span> fast = head;
<span class="keyword">while</span> (fast !== <span class="keyword">null</span> && fast.next !== <span class="keyword">null</span>) {
slow = slow.next; <span class="comment">// Move 1 step</span>
fast = fast.next.next; <span class="comment">// Move 2 steps</span>
<span class="keyword">if</span> (slow === fast) {
<span class="keyword">return true</span>; <span class="comment">// Cycle detected</span>
}
}
<span class="keyword">return false</span>; <span class="comment">// No cycle</span>
}</code></pre>
<h3>Find Middle of a Linked List</h3>
<p>When fast reaches the end, slow is at the middle. If the list has even length, slow will be at the second of the two middle nodes.</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">find_middle</span>(head):
<span class="comment">"""Return middle node. O(n) time, O(1) space."""</span>
slow = head
fast = head
<span class="keyword">while</span> fast <span class="keyword">and</span> fast.next:
slow = slow.next
fast = fast.next.next
<span class="keyword">return</span> slow <span class="comment"># slow is now at the middle</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">findMiddle</span>(head) {
<span class="keyword">let</span> slow = head;
<span class="keyword">let</span> fast = head;
<span class="keyword">while</span> (fast !== <span class="keyword">null</span> && fast.next !== <span class="keyword">null</span>) {
slow = slow.next;
fast = fast.next.next;
}
<span class="keyword">return</span> slow;
}</code></pre>
<div class="example-box">
<div class="label">Why does this work?</div>
<p>Fast moves 2x the speed of slow. When fast has traversed the entire list (n steps), slow has traversed n/2 steps -- exactly the middle.</p>
</div>
<!-- --- REVERSING A LINKED LIST --- -->
<h3>Reversing a Linked List (Iterative)</h3>
<p>This is one of the most important linked list operations. We use <strong>three pointers</strong>: <code>prev</code>, <code>curr</code>, and <code>next_node</code>. At each step, we reverse one link.</p>
<h3>Step-by-Step Visual Walkthrough</h3>
<div class="formula-box">
<strong>Original:</strong> 1 -> 2 -> 3 -> 4 -> null<br><br>
<strong>Step 1:</strong> prev=null, curr=1, next=2<br>
Reverse: 1.next = null<br>
Move: prev=1, curr=2<br>
Result: null <- 1 2 -> 3 -> 4 -> null<br><br>
<strong>Step 2:</strong> prev=1, curr=2, next=3<br>
Reverse: 2.next = 1<br>
Move: prev=2, curr=3<br>
Result: null <- 1 <- 2 3 -> 4 -> null<br><br>
<strong>Step 3:</strong> prev=2, curr=3, next=4<br>
Reverse: 3.next = 2<br>
Move: prev=3, curr=4<br>
Result: null <- 1 <- 2 <- 3 4 -> null<br><br>
<strong>Step 4:</strong> prev=3, curr=4, next=null<br>
Reverse: 4.next = 3<br>
Move: prev=4, curr=null<br>
Result: null <- 1 <- 2 <- 3 <- 4<br><br>
<strong>Done!</strong> curr is null, return prev (4) as new head.
</div>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">reverse_list</span>(head):
<span class="comment">"""Reverse a singly linked list. O(n) time, O(1) space."""</span>
prev = <span class="keyword">None</span>
curr = head
<span class="keyword">while</span> curr:
next_node = curr.next <span class="comment"># Save next</span>
curr.next = prev <span class="comment"># Reverse the link</span>
prev = curr <span class="comment"># Move prev forward</span>
curr = next_node <span class="comment"># Move curr forward</span>
<span class="keyword">return</span> prev <span class="comment"># prev is the new head</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">reverseList</span>(head) {
<span class="keyword">let</span> prev = <span class="keyword">null</span>;
<span class="keyword">let</span> curr = head;
<span class="keyword">while</span> (curr !== <span class="keyword">null</span>) {
<span class="keyword">const</span> nextNode = curr.next; <span class="comment">// Save next</span>
curr.next = prev; <span class="comment">// Reverse the link</span>
prev = curr; <span class="comment">// Move prev forward</span>
curr = nextNode; <span class="comment">// Move curr forward</span>
}
<span class="keyword">return</span> prev; <span class="comment">// prev is the new head</span>
}</code></pre>
<div class="warning-box">
<div class="label">Common Mistake</div>
<p>Forgetting to save <code>curr.next</code> before overwriting it. If you set <code>curr.next = prev</code> first, you lose the reference to the rest of the list. Always save the next pointer first.</p>
</div>
<!-- --- MERGING TWO SORTED LISTS --- -->
<h3>Merging Two Sorted Linked Lists</h3>
<p>Use a <strong>two-pointer approach</strong> with a dummy head node. Compare current nodes from both lists, attach the smaller one to the merged list, and advance that pointer.</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">merge_two_lists</span>(l1, l2):
<span class="comment">"""Merge two sorted lists into one sorted list."""</span>
dummy = <span class="builtin">Node</span>(<span class="number">0</span>) <span class="comment"># Dummy head simplifies edge cases</span>
current = dummy
<span class="keyword">while</span> l1 <span class="keyword">and</span> l2:
<span class="keyword">if</span> l1.data <= l2.data:
current.next = l1
l1 = l1.next
<span class="keyword">else</span>:
current.next = l2
l2 = l2.next
current = current.next
<span class="comment"># Attach the remaining nodes</span>
current.next = l1 <span class="keyword">if</span> l1 <span class="keyword">else</span> l2
<span class="keyword">return</span> dummy.next <span class="comment"># Skip the dummy node</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">mergeTwoLists</span>(l1, l2) {
<span class="keyword">const</span> dummy = <span class="keyword">new</span> <span class="builtin">Node</span>(<span class="number">0</span>);
<span class="keyword">let</span> current = dummy;
<span class="keyword">while</span> (l1 !== <span class="keyword">null</span> && l2 !== <span class="keyword">null</span>) {
<span class="keyword">if</span> (l1.data <= l2.data) {
current.next = l1;
l1 = l1.next;
} <span class="keyword">else</span> {
current.next = l2;
l2 = l2.next;
}
current = current.next;
}
<span class="comment">// Attach remaining nodes</span>
current.next = l1 !== <span class="keyword">null</span> ? l1 : l2;
<span class="keyword">return</span> dummy.next;
}</code></pre>
<div class="tip-box">
<div class="label">Dummy Node Trick</div>
<p>The dummy node eliminates special-case handling for the first node. Instead of checking "is the merged list empty?", we always have a node to attach to. At the end, we return <code>dummy.next</code> to skip it.</p>
</div>
</section>
<!-- ======================= SECTION 6 ======================= -->
<section id="leetcode">
<h2>6. LeetCode Problems</h2>
<p>These are the essential linked list problems. Master these and you will handle most linked list interview questions.</p>
<table>
<thead>
<tr>
<th>Problem</th>
<th>Difficulty</th>
<th>Key Technique</th>
</tr>
</thead>
<tbody>
<tr>
<td>206. Reverse Linked List</td>
<td><span class="tag green">Easy</span></td>
<td>Three pointers (prev, curr, next)</td>
</tr>
<tr>
<td>21. Merge Two Sorted Lists</td>
<td><span class="tag green">Easy</span></td>
<td>Two pointers + dummy node</td>
</tr>
<tr>
<td>141. Linked List Cycle</td>
<td><span class="tag green">Easy</span></td>
<td>Fast/slow pointers</td>
</tr>
<tr>
<td>19. Remove Nth Node From End</td>
<td><span class="tag orange">Medium</span></td>
<td>Two pointers with n-gap</td>
</tr>
<tr>
<td>143. Reorder List</td>
<td><span class="tag orange">Medium</span></td>
<td>Find middle + reverse second half + merge</td>
</tr>
<tr>
<td>2. Add Two Numbers</td>
<td><span class="tag orange">Medium</span></td>
<td>Traverse both lists, carry digit</td>
</tr>
<tr>
<td>146. LRU Cache</td>
<td><span class="tag orange">Medium</span></td>
<td>Doubly linked list + hash map</td>
</tr>
</tbody>
</table>
<!-- --- FULL SOLUTION: Reverse Linked List --- -->
<h3>206. Reverse Linked List (Full Solution)</h3>
<p><strong>Problem:</strong> Given the head of a singly linked list, reverse the list and return the reversed list.</p>
<p><strong>Approach:</strong> Use three pointers -- <code>prev</code>, <code>curr</code>, and <code>next_node</code>. Walk through the list, reversing each link as you go. When <code>curr</code> becomes null, <code>prev</code> points to the new head.</p>
<div class="example-box">
<div class="label">Example</div>
<p>Input: 1 -> 2 -> 3 -> 4 -> 5 -> null<br>
Output: 5 -> 4 -> 3 -> 2 -> 1 -> null</p>
</div>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">class</span> <span class="builtin">Solution</span>: