在 tikz 中排版经典数据结构

在 tikz 中排版经典数据结构

在这讨论Christian R. 给出了使用 TikZ 生成的示例图像,但没有提供代码:

在此处输入图片描述

如果有实现它的代码片段就太好了,因为我认为它具有排版命令式语言中最常见数据结构的基本部分。

答案1

嗯,我想我可以帮忙。:-)

代码

\documentclass{scrartcl}

\usepackage{tikz}
\usetikzlibrary{shapes,arrows,calc}
\newcommand{\data}{data \nodepart{second} \phantom{null}}

\tikzstyle{ptr}  = [draw, -latex']
\tikzstyle{head} = [rectangle, draw, text height=3mm, text width=3mm, text centered, node distance=3cm, inner sep=0pt]
\tikzstyle{data} = [rectangle split, rectangle split parts=2, draw, text centered, minimum height=3em]

\begin{document}

\begin{tikzpicture}[node distance=2cm, auto]

    \node[head, label=below:head] (head) {};
    \node[data, right of=head]    (A) {\data};
    \node[data, right of=A]       (B) {\data};
    \node[data, right of=B]       (C) {\data};
    \node[above of=C,head,node distance=2cm,label=above:prev]   (prev){};
    \node[data, right of=C]       (D) {\data};
    \node[above of=D,head,node distance=2cm,label=above:curr]   (curr){};
    \node[data, right of=D]       (E) {\data};
    \node[data, right of=E]       (last) {data \nodepart{second} null};

    \draw[fill] (head.center)   circle (0.05);
    \draw[fill] (prev.center)   circle (0.05);
    \draw[fill] (curr.center)   circle (0.05);

    \path[ptr]  (head.center) --++(right:7.5mm)  |- (A.text west);
    \draw[fill] ($(A.south)!0.5!(A.text split)$) circle (0.05);
    \draw[ptr]  ($(A.south)!0.5!(A.text split)$) --++(right:10mm) |- (B.text west);
    \draw[fill] ($(B.south)!0.5!(B.text split)$) circle (0.05);
    \draw[ptr]  ($(B.south)!0.5!(B.text split)$) --++(right:10mm) |- (C.text west);
    \path[ptr] (prev) -- (C);
    \draw[fill] ($(C.south)!0.5!(C.text split)$) circle (0.05);
    \draw[ptr]  ($(C.south)!0.5!(C.text split)$) --++(right:10mm) |- (D.text west);
    \path[ptr] (curr) -- (D);
    \draw[fill] ($(D.south)!0.5!(D.text split)$) circle (0.05);
    \draw[ptr]  ($(D.south)!0.5!(D.text split)$) --++(right:10mm) |- (E.text west);
    \draw[fill] ($(E.south)!0.5!(E.text split)$) circle (0.05);
    \draw[ptr]  ($(E.south)!0.5!(E.text split)$) --++(right:10mm) |- (last.text west);

\end{tikzpicture}

\end{document}

结果(尽管在问题中已经可以看到)

图像

我很确定代码可以简化,因此欢迎改进。

相关内容