Programming in C

(Barry) #1
Working with Pointers and Structures 249

Inserting an element into a list is just as straightforward. If you want to insert a struct
entrycalled n2_3after n2in the list, you can simply set n2_3.nextto point to whatever
n2.nextwas pointing to, and then set n2.nextto point to n2_3.So, the sequence of
statements


n2_3.next = n2.next;
n2.next = &n2_3;


inserts n2_3into the list, immediately after entry n2. Note that the sequence of the pre-
ceding statements is important because executing the second statement first overwrites
the pointer stored in n2.nextbefore it has a chance to be assigned to n2_3.next.The
inserted element n2_3is depicted in Figure 11.7. Notice that n2_3is not shown
between n1and n3.This is to emphasize that n2_3can be anywhere in memory and
does not have to physically occur after n1and before n3.This is one of the main motiva-
tions for the use of a linked list approach for storing information: Entries of the list do
not have to be stored sequentially in memory, as is the case with elements in an array.


n1

value
next

n2

value
next

n3

value
next

n2_3

value
next

Figure 11.7 Inserting an element into a linked list.
Free download pdf