-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0206_reverse_linked_list.html
More file actions
375 lines (312 loc) · 12.8 KB
/
0206_reverse_linked_list.html
File metadata and controls
375 lines (312 loc) · 12.8 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LC 206: Reverse Linked List - Algorithm Visualization</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class="container">
<div class="problem-info">
<h1><span class="problem-number">#206</span> Reverse Linked List</h1>
<p>Given the head of a singly linked list, reverse the list and return the reversed list.</p>
<div class="problem-meta">
<span class="meta-tag">🔗 Linked List</span>
<span class="meta-tag">⏱️ O(n)</span>
<span class="meta-tag">💾 O(1)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0206_reverse_linked_list/0206_reverse_linked_list.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Imagine a chain of train cars pointing one direction. We want to reverse them:</p>
<ul>
<li><strong>prev:</strong> The car we've already processed (starts as None)</li>
<li><strong>curr:</strong> The car we're currently working on</li>
<li><strong>temp:</strong> Temporary save of next car before we change the link</li>
<li><strong>Process:</strong> Disconnect current from next, point it backwards to prev</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button class="btn btn-primary" id="stepBtn" onclick="step()">Step</button>
<button class="btn btn-success" id="autoBtn" onclick="toggleAuto()">Auto Run</button>
<button class="btn btn-warning" onclick="reset()">Reset</button>
</div>
<div class="status-message" id="statusMessage">
Click "Step" or "Auto Run" to start visualization
</div>
<div class="variable-display">
<div class="variable-box">
<div class="variable-name">prev</div>
<div class="variable-value" id="prevVal" style="color: #9c27b0;">None</div>
</div>
<div class="variable-box">
<div class="variable-name">curr</div>
<div class="variable-value" id="currVal" style="color: #ff5722;">1</div>
</div>
<div class="variable-box">
<div class="variable-name">temp</div>
<div class="variable-value" id="tempVal" style="color: #2196f3;">-</div>
</div>
</div>
<div class="array-section">
<div class="array-label">🔗 Original List:</div>
<div id="originalList" class="linked-list-container"></div>
</div>
<div class="array-section">
<div class="array-label">🔄 Reversed Part (prev chain):</div>
<div id="reversedList" class="linked-list-container">
<span style="color: #999;">None</span>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution (Iterative)</h3>
<div class="code-block">
<pre>from typing import List, Optional
"""
LeetCode 206. Reverse Linked List
Problem from LeetCode: https://leetcode.com/problems/reverse-linked-list/
Description:
Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2]
Output: [2,1]
Example 3:
Input: head = []
Output: []
Constraints:
- The number of nodes in the list is the range [0, 5000].
- -5000 <= Node.val <= 5000
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
"""
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverse_list(self, head: ListNode) ->ListNode:
"""
Reverse a singly linked list.
Args:
head: Head of the linked list
Returns:
ListNode: Head of the reversed linked list
"""
prev = None
curr = head
while curr is not None:
temp = curr.next
curr.next = prev
prev = curr
curr = temp
return prev
def reverse_list_recursive(self, head: ListNode) ->ListNode:
"""
Reverse a singly linked list using recursion.
Args:
head: Head of the linked list
Returns:
ListNode: Head of the reversed linked list
"""
if head is None or head.next is None:
return head
new_head = self.reverse_list_recursive(head.next)
head.next.next = head
head.next = None
return new_head
# Helper function to create a linked list from an array
def create_linked_list(arr):
if not arr:
return None
head = ListNode(arr[0])
current = head
for val in arr[1:]:
current.next = ListNode(val)
current = current.next
return head
# Helper function to convert a linked list to an array
def linked_list_to_array(head):
result = []
current = head
while current:
result.append(current.val)
current = current.next
return result
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
arr1 = [1, 2, 3, 4, 5]
head1 = create_linked_list(arr1)
print(f"Input: head = {arr1}")
reversed_head1 = solution.reverse_list(head1)
result1 = linked_list_to_array(reversed_head1)
print(f"Output (iterative): {result1}") # Expected output: [5,4,3,2,1]
# Example 2
arr2 = [1, 2]
head2 = create_linked_list(arr2)
print(f"\nInput: head = {arr2}")
reversed_head2 = solution.reverse_list(head2)
result2 = linked_list_to_array(reversed_head2)
print(f"Output (iterative): {result2}") # Expected output: [2,1]
# Example 3
arr3 = []
head3 = create_linked_list(arr3)
print(f"\nInput: head = {arr3}")
reversed_head3 = solution.reverse_list(head3)
result3 = linked_list_to_array(reversed_head3)
print(f"Output (iterative): {result3}") # Expected output: []
# Test recursive solution with Example 1
head1_rec = create_linked_list(arr1)
reversed_head1_rec = solution.reverse_list_recursive(head1_rec)
result1_rec = linked_list_to_array(reversed_head1_rec)
print(f"\nOutput (recursive): {result1_rec}") # Expected output: [5,4,3,2,1]
</pre>
</div>
</div>
</div>
<script>
const values = [1, 2, 3, 4, 5];
let nodes = values.map(v => ({ val: v }));
let prev = null;
let prevIndex = -1;
let currIndex = 0;
let autoInterval = null;
let reversedNodes = [];
function init() {
renderOriginalList();
renderReversedList();
}
function renderOriginalList() {
const container = document.getElementById('originalList');
container.innerHTML = '';
for (let i = currIndex; i < values.length; i++) {
const nodeDiv = document.createElement('div');
nodeDiv.className = 'list-node';
const box = document.createElement('div');
box.className = 'node-box';
box.textContent = values[i];
if (i === currIndex) {
box.classList.add('current');
}
nodeDiv.appendChild(box);
if (i < values.length - 1) {
const arrow = document.createElement('span');
arrow.className = 'node-arrow';
arrow.textContent = '→';
nodeDiv.appendChild(arrow);
}
container.appendChild(nodeDiv);
}
if (currIndex >= values.length) {
container.innerHTML = '<span class="null-node">None (empty)</span>';
} else {
const nullSpan = document.createElement('span');
nullSpan.className = 'null-node';
nullSpan.textContent = '→ None';
container.appendChild(nullSpan);
}
}
function renderReversedList() {
const container = document.getElementById('reversedList');
container.innerHTML = '';
if (reversedNodes.length === 0) {
container.innerHTML = '<span class="null-node">None</span>';
return;
}
for (let i = 0; i < reversedNodes.length; i++) {
const nodeDiv = document.createElement('div');
nodeDiv.className = 'list-node';
const box = document.createElement('div');
box.className = 'node-box visited';
box.textContent = reversedNodes[i];
nodeDiv.appendChild(box);
if (i < reversedNodes.length - 1) {
const arrow = document.createElement('span');
arrow.className = 'node-arrow';
arrow.textContent = '→';
nodeDiv.appendChild(arrow);
}
container.appendChild(nodeDiv);
}
const nullSpan = document.createElement('span');
nullSpan.className = 'null-node';
nullSpan.textContent = '→ None';
container.appendChild(nullSpan);
}
function step() {
if (currIndex >= values.length) {
document.getElementById('statusMessage').className = 'status-message success';
document.getElementById('statusMessage').textContent =
`✅ Done! Reversed list: [${reversedNodes.join(' → ')}]`;
document.getElementById('stepBtn').disabled = true;
stopAuto();
return;
}
const currVal = values[currIndex];
const nextVal = currIndex + 1 < values.length ? values[currIndex + 1] : 'None';
document.getElementById('tempVal').textContent = nextVal;
document.getElementById('statusMessage').textContent =
`temp = ${nextVal}, curr(${currVal}).next = prev(${prev !== null ? prev : 'None'}), ` +
`prev = ${currVal}, curr = ${nextVal}`;
// Update reversed list
reversedNodes.unshift(currVal);
// Move pointers
prev = currVal;
currIndex++;
// Update displays
document.getElementById('prevVal').textContent = prev;
document.getElementById('currVal').textContent = currIndex < values.length ? values[currIndex] : 'None';
renderOriginalList();
renderReversedList();
}
function toggleAuto() {
if (autoInterval) {
stopAuto();
} else {
document.getElementById('autoBtn').textContent = 'Pause';
autoInterval = setInterval(() => {
if (currIndex >= values.length) {
step();
stopAuto();
} else {
step();
}
}, 1200);
}
}
function stopAuto() {
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
}
document.getElementById('autoBtn').textContent = 'Auto Run';
}
function reset() {
stopAuto();
prev = null;
prevIndex = -1;
currIndex = 0;
reversedNodes = [];
document.getElementById('stepBtn').disabled = false;
document.getElementById('statusMessage').className = 'status-message';
document.getElementById('statusMessage').textContent = 'Click "Step" or "Auto Run" to start visualization';
document.getElementById('prevVal').textContent = 'None';
document.getElementById('currVal').textContent = values[0];
document.getElementById('tempVal').textContent = '-';
init();
}
init();
</script>
</body>
</html>