Singly-linked list/Element insertion

From Rosetta Code
Revision as of 22:43, 20 March 2007 by Ce (talk | contribs) (C++)
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);

C++

This uses the generic version of the link node. Of course, normally this would be just some implementation detail inside some list class, not to be used directly by client code.

template<typename T> void insert_after(link<T>* list_node, link<T>* new_node)
{
  new_node->next = list_node->next;
  list_node->next = new_node;
};

Here's the example code using that method:

The following code creates the links. As numeric values I've just taken the corresponding character values.

link<int>* a = new link('A', new link('B'));
link<int>* c = new link('C');

Now insert c after a:

insert_after(a, c);

Finally destroy the list:

while (a)
{
  link<int>* tmp = a;
  a = a->next;
  delete tmp;
}