Singly-linked list/Element insertion

From Rosetta Code
Revision as of 18:57, 20 March 2007 by MikeMol (talk | contribs) (Created article, started with C example.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Singly-linked list/Element insertion
You are encouraged to solve this task according to the task description, using any language you may know.

Using the link element defined in Singly-Linked List (element), define a method to insert an element into a singly-linked list following a given element.

Using this method, insert an element C into a list comprised of elements A->B, following element A.

C

Define the method:

void insert_append (link *anchor, link *newlink) {
  newbie->next = anchor->next;
  anchor->next = newlink;
}

Note that in a production implementation, one should check anchor and newlink to ensure they're valid values. (I.e., not NULL.)

And now on to the code.

Create our links.

link *a, *b, *c;
a = malloc(sizeof(link));
b = malloc(sizeof(link));
c = malloc(sizeof(link));
a->data = 1;
b->data = 2;
c->data = 3;

Prepare our initial list

insert_append (a, b);

Insert element c after element a

insert_append (a, c); 

Remember to free the memory once we're done.

free (a);
free (b);
free (c);