File size: 1,566 Bytes
26ee80c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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