Anyone can help?

T

Tinker

If we used an array of many structures such as:

struct instruction array[1000];

and this array holds 500 instructions from array[0] to array[499], how
can a new instruction be inserted between the 2nd and 3rd
instructions? Why is a linked list preferable in this situation?

please help
thanks
 
J

Joona I Palaste

Tinker said:
If we used an array of many structures such as:
struct instruction array[1000];
and this array holds 500 instructions from array[0] to array[499], how
can a new instruction be inserted between the 2nd and 3rd
instructions? Why is a linked list preferable in this situation?

You'll have to move the other instructions by hand to make room for the
new instruction. This would involve 498 assignment operations.
A linked list is preferable because in a linked list, insertion (once
you know where to insert) takes O(1) time instead of O(n). You simply
assign one pointer to point somewhere else. For details, ask your
teacher.
 
D

David Resnick

Tinker said:
If we used an array of many structures such as:

struct instruction array[1000];

and this array holds 500 instructions from array[0] to array[499], how
can a new instruction be inserted between the 2nd and 3rd
instructions? Why is a linked list preferable in this situation?

please help
thanks

Inserting into arrays requires copying the array elements
at and beyond the insertion point. This can be expensive.
For example, in your case, you'd have to do something like:
/* copy elements upwards */
memmove(&array[3], &array[2], sizeof(struct instruction) * 498);
/* fill in new instruction */
array[2].field1 = 1;
array[2].field2 = 2; /* ... */

Whether this is a good idea depends on your application. If you
are inserting relatively rarely, want random access, and don't
care about pointers to individual instructions getting invalidated
by the copying, well, the array may be what you want.

If you are inserting often, don't care about random access, and want
insertion not to invalidate pointers to individual members, a linked
list is a fine choice. Insertion just involves fiddling with a few
pointers.

-David
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,147
Messages
2,570,835
Members
47,383
Latest member
EzraGiffor

Latest Threads

Top