# array of linked lists like in data structure

I want to implement an array of linked lists in La TeX like it appeared in data structure (graphic):

the array elements are the numbers{1,2,3} and every number in the array is ahead of linked list{the first element in array is the head of the linked list a->b->null, where a and b are the nodes in the linked list, and so on to the other array elements}

|1|->a->b->null

|2|->c->null

|3|->d->null

can you help me in this?

-
Are you trying to draw this as a graphic, or just as something in text? Are you looking for a way to input this using a macro (say) \linkedlist{1={a,b,null},2={c,null},3={d,null}} and the output should be automated? –  Werner Dec 12 '12 at 22:53
I want to draw it as a graphic –  Ahmed Mojaz Dec 13 '12 at 7:47
Also you might be interested in: tex.stackexchange.com/a/44267/1410 –  morbusg Dec 13 '12 at 9:17
add comment

## 1 Answer

I tried to write a code which provides the simplest interface:

\begin{tikzpicture}
\foreach \index/\list in {1/{a,b,null}, 2/{c,null}, 3/{d,null}} {
\node[array element] (aux) at (0,-\index) {\index};
\LinkedList{\list}
}
\end{tikzpicture}


This is the complete source code:

\documentclass{article}
\usepackage{tikz}
\begin{document}
\thispagestyle{empty}
\usetikzlibrary{positioning}
\tikzset{
node of list/.style = {
draw,
fill=orange!20,
minimum height=6mm,
minimum width=6mm,
node distance=6mm
},
link/.style = {
-stealth,
shorten >=1pt
},
array element/.style = {
draw, fill=white,
minimum width = 6mm,
minimum height = 10mm
}
}

\def\LinkedList#1{%
\foreach \element in \list {
\node[node of list, right = of aux, name=\element] {\element};
\draw[link] (aux) -- (\element);
\coordinate (aux) at (\element.east);
}
}

\begin{tikzpicture}
\foreach \index/\list in {1/{a,b,null}, 2/{c,null}, 3/{d,null}} {
\node[array element] (aux) at (0,-\index) {\index};
\LinkedList{\list}
}
\end{tikzpicture}
\end{document}


However, the above is not the standard way of representing linked lists. I prefer this one instead:

Which is obtained simply replacing the definition of \LinkedList above for this one:

\def\LinkedList#1{%
\foreach \element in \list {
\node[node of list, right = of aux, name=\element] {\element};
\node[node of list, name=aux2, anchor=west] at ([xshift=-.4pt] \element.east) {};
\draw[link] (aux) -- (\element);
\coordinate (aux) at (aux2);
}
\fill (aux) circle(2pt);
}


and removing the null element in the list specification, i.e. the main loop is now:

\foreach \index/\list in {1/{a,b}, 2/{c}, 3/{d}} {

-
thanks alot man –  Ahmed Mojaz Dec 13 '12 at 11:12
add comment