我正在尝试使用 TikZ 创建链接列表。我目前有这个:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{chains,shapes}
\newcommand{chainlabel}[2]{\path [<-, draw, shorten >=10pt] #1 |- node [at end] {#2} ++(-1,1);}
\begin{document}
\begin{tikzpicture}[every node/.style={rectangle split, rectangle split parts=2, rectangle split horizontal}, node distance=1em, start chain,
every join/.style={->, shorten <=-4.5pt}]
\node[draw, on chain, join] { 1 };
\node[draw, on chain, join] { 7 };
\node[draw, on chain, join] { 5 };
\node[draw, on chain, join] { 2 };
\node[draw, on chain, join] {};
\chainlabel{chain-1.one north}{head};
\end{tikzpicture}
\end{document}
问题出在chainlabel
命令上。我收到各种有关缺少控制序列的错误。我读到过需要某种expandafter
东西,但我不知道如何使用它。
ps chainlabel 背后的想法是我们可以将一个坐标传递给命令和一个标签,它会用提供的文本标记节点。
答案1
您在命令定义中犯了一些错误:您忘记了初始反斜杠(而是\chainlabel
)chainlabel
,并且由于您使用了\path #1 |- ...
第一个参数,因此应该有括号,除非您使用\path (#1) |- ...
,就像我在下面的例子中所做的那样:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{chains,shapes}
\newcommand{\chainlabel}[2]{\path [<-, draw, shorten >=10pt] (#1) |- node [at end] {#2} ++(-1,1);}
\begin{document}
\begin{tikzpicture}[every node/.style={rectangle split, rectangle split parts=2, rectangle split horizontal}, node distance=1em, start chain,
every join/.style={->, shorten <=-4.5pt}]
\node[draw, on chain, join] { 1 };
\node[draw, on chain, join] { 7 };
\node[draw, on chain, join] { 5 };
\node[draw, on chain, join] { 2 };
\node[draw, on chain, join] {};
\chainlabel{chain-1.one north}{head};
\end{tikzpicture}
\end{document}
也许你可以添加一些minimum height
,rectangle split
这样即使是空的,它们也会有一个统一的大小:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{chains,shapes}
\newcommand{\chainlabel}[2]{\path [<-, draw, shorten >=10pt] (#1) |- node [at end] {#2} ++(-1,1);}
\begin{document}
\begin{tikzpicture}[every node/.style={rectangle split, rectangle split parts=2, rectangle split horizontal,minimum height=14pt}, node distance=1em, start chain,
every join/.style={->, shorten <=-4.5pt}]
\node[draw, on chain, join] { 1 };
\node[draw, on chain, join] { 7 };
\node[draw, on chain, join] { 5 };
\node[draw, on chain, join] { 2 };
\node[draw, on chain, join] {};
\chainlabel{chain-1.one north}{head};
\end{tikzpicture}
\end{document}