# How to fix the alignment of table cells?

While trying to improve the answer for another question, I am stuck at getting proper horizontal alignment. The alignment problem is evident in second column. It also shows up as difference in spacing of element 16 and 12(or 26) from the arrow. Why is this happening and how can I fix it?

\documentclass{standalone}

\usepackage{amsmath}
\usepackage{array}

\newsavebox{\boxname}
\newcolumntype{B}{@{}>{\begin{lrbox}{\boxname}}c%
<{\end{lrbox}{\fbox{\unhbox\boxname}}}}
\newcommand{\dummy}{\phantom{01}}
\newcommand{\lastelem}[1]{\multicolumn{1}{B}{#1}}

\begin{document}

\begin{tabular}{c @{ } B *2{ @{$\to$} B }}
1 & \lastelem{\dummy}                                     \\
2 & \dummy              & \lastelem{16}                   \\
4 & \lastelem{\dummy}                                     \\
5 & \dummy              & 12             & \lastelem{26}  \\
\end{tabular}

\end{document}


Interestingly the problem is present when I try,

\begin{tabular}{c}
\lastelem{\dummy} \\
\fbox{\dummy} \\
\end{tabular}


This gives "reverse" indentation than the previous table. However the following works fine.

\begin{tabular}{B}
\lastelem{\dummy} \\
\dummy \\
\end{tabular}


Output of other cases,

-
Okay I figure out the reason for second example. My column definition was not "balanced". Adding @{} at the end of \newcolumntype{B}{@{}>{\begin{lrbox}{\boxname}}c<{\end{lrbox}{\fbox{\unhbox\box‌​name}}}} fixes the problem. But I still have problem with the main example. –  mythealias Oct 24 '12 at 8:45

You need to keep the size of your @ expressions the same, you had, at various points, nothing{} a word space { } and an arrow {$\to$}

\documentclass{standalone}

\usepackage{amsmath}
\usepackage{array}

\newsavebox{\boxname}
\newcolumntype{B}{@{}>{\begin{lrbox}{\boxname}}c%
<{\end{lrbox}{\fbox{\unhbox\boxname}}}}
\newcommand{\dummy}{\phantom{01}}
\newcommand{\lastelem}[1]{\multicolumn{1}{B@{$\phantom{\to}$}}{#1}\ignorespaces}

\begin{document}

\begin{tabular}{c @{} B *2{ @{$\to$} B }}
1 & \lastelem{\dummy}                                     \\
2 & \dummy              & \lastelem{16}                   \\
4 & \lastelem{\dummy}                                     \\
5 & \dummy              & 12             & \lastelem{26}  \\
\end{tabular}

\end{document}

-
Thank you. I had added @{ } to get some space between first and second column. I can do this by adding \phantom{0} to first element and changing alignment from c to l. Is there another way to add space between these two column? –  mythealias Oct 24 '12 at 16:10
you can put the { } back but put the same space in all multicolumn specifications that cross that column boundary, so things line up,, or simpler put it in the first column instead so c<{\mbox{\hspace*{2em}}} or something –  David Carlisle Oct 24 '12 at 17:03