Singly-linked list/Element insertion
Singly-linked list/Element insertion
You are encouraged to solve this task according to the task description, using any language you may know.
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);