Programming in C

(Barry) #1

248 Chapter 11 Pointers


both operators are used, the operators are evaluated from left to right.Therefore, the
expression is evaluated as
i = (n1.next)->value;
which is what was intended.
The second printfcall in Program 11.6 displays the valuemember that is pointed
to by n2.next. Because you set n2.nextto point to n3, the contents of n3.valueare
displayed by the program.
As mentioned, the concept of a linked list is a very powerful one in programming.
Linked lists greatly simplify operations such as the insertion and removal of elements
from large lists of sorted items.
For example, if n1,n2,and n3are as defined previously, you can easily remove n2from
the list simply by setting the nextfield of n1to point to whatever n2is pointing to:
n1.next = n2.next;
This statement has the effect of copying the pointer contained in n2.nextinto n1.next,
and, because n2.nextwas set to point to n3,n1.nextis now pointing to n3.
Furthermore, because n1no longer points to n2,you have effectively removed it from
your list. Figure 11.6 depicts this situation after the preceding statement is executed. Of
course, you could have set n1pointing to n3directly with the statement
n1.next = &n3;
but this latter statement is not as general because you must know in advance that n2is
pointing to n3.

n1

value
next

n2

value
next

n3

value
next

Figure 11.6 Removing an entry from a linked list.
Free download pdf