Umm... the code shall set you free.
Code:
#define NODESIZE sizeof (struct identnode)
struct identnode
{
int ident;
struct identnode * next;
}
void addFirst (int ident); // Adds structure to beginning of list
void addLast (int ident); // Adds to end
void addAfter (int ident, int seek); // Adds after occourance
// of ident
int getNth (int nth); // Returns the nth ident in list.. nth starts
// at 0, like an array
struct identnode * list = NULL; // List points to the first node...
// But the list is empty. Global to make life easier.
int main ()
{
addFirst (6); // list is {6}
addFirst (4); // list is {4, 6}
addLast (7); // list is {4, 6, 7}
addAfter (2, 6); // list is {4, 6, 2, 7}
return getNth (1); // returns 6
}
void addFirst (int ident)
{
struct identnode * p = malloc (NODESIZE);
p -> ident = ident;
p -> next = list;
list = p;
return;
}
// WARNING, this code doesn't work on an empty list.
void addLast (int ident)
{
struct identnode * p = malloc (NODESIZE);
struct identnode * q;
p -> ident = ident;
p -> next = NULL; // NULL because it's the last element
for (q = list; q -> next != NULL; q = q -> next);
// Now q points to the last node.
q -> next = p;
return;
}
// WARNING, this doesn't work if seek is not in list.
void addAfter (int ident, int seek)
{
struct identnode * p = malloc (NODESIZE);
struct identnode * q;
p -> ident = ident;
for (q = list; q -> ident != seek; q = q -> next);
// Now q points to node containing seek
p -> next = q -> next;
q -> next = p;
return;
}
// WARNING, this doesn't work if nth is too big.
int getNth (int nth)
{
struct identnode * q;
for (q = list; n != 0; q = q -> next, n--);
return q -> ident;
}
Haven't compiled the code, but it all looks kosher to me. A thing about linked lists is that you almost never have to allocate memory for one of the nodes by using "struct list new_list"; it's all pointers and malloc.
The point of lists is just to have a way to store information, in my example's case, integers, in a manner that allows you to insert information wherever you wish.
EDIT: Hope it doesn't mess up window anymore...