Spaces:
Sleeping
Sleeping
| import base64 | |
| from io import BytesIO | |
| from PIL import Image, ImageDraw, ImageFont | |
| def draw_linked_list_frame(nodes): | |
| """ | |
| Given a list of node values (strings), return a PIL Image representing the current state. | |
| """ | |
| width = max(600, len(nodes) * 120) | |
| img = Image.new('RGB', (width, 100), color='white') | |
| draw = ImageDraw.Draw(img) | |
| font = ImageFont.load_default() | |
| for i, val in enumerate(nodes): | |
| x0 = i * 100 + 10 | |
| # Draw node rectangle | |
| draw.rectangle([x0, 30, x0 + 80, 70], outline='black', width=2) | |
| draw.text((x0 + 25, 40), val, fill='black', font=font) | |
| # Draw arrow to next node if exists | |
| if i < len(nodes) - 1: | |
| draw.line((x0 + 80, 50, x0 + 100, 50), fill='black', width=2) | |
| return img | |
| def generate_linked_list_gif(operations, output_path): | |
| """ | |
| Given a list of operations like ["insert 5", "insert 10", "delete"], build a sequence of frames, | |
| then save as an animated GIF to output_path. | |
| """ | |
| frames = [] | |
| nodes = [] | |
| for op in operations: | |
| parts = op.split() | |
| if len(parts) >= 2 and parts[0] == "insert": | |
| nodes.append(parts[1]) | |
| elif parts[0] == "delete": | |
| if nodes: | |
| nodes.pop(0) # delete head | |
| # Draw current state | |
| img = draw_linked_list_frame(nodes) | |
| frames.append(img) | |
| # Save frames as GIF | |
| frames[0].save( | |
| output_path, | |
| save_all=True, | |
| append_images=frames[1:], | |
| duration=800, | |
| loop=0 | |
| ) | |
| return output_path | |