The following program finds the sum of the integer numbers in a linked list:
/** ** Example program illustrating structures using linked lists **/ #include <stdio.h> struct record { int number; struct record *next_num; }; int main(void) { struct record name1, name2, name3; struct record *recd_pointer = &name1; int sum = 0; name1.number = 144; name2.number = 203; name3.number = 488; name1.next_num = &name2; name2.next_num = &name3; name3.next_num = NULL; while (recd_pointer != NULL) { sum += recd_pointer->number; recd_pointer = recd_pointer->next_num; } printf("Sum = %d\n", sum); return(0); }
The structure type record contains two members: the integer number and next_num, which is a pointer to a structure variable of type record.
The record type variables name1, name2, and name3 are assigned the following values:
The variable recd_pointer is a pointer to a structure of type record. It is initialized to the address of name1 (the beginning of the linked list).
The while loop causes the linked list to be scanned until recd_pointer equals NULL. The statement:
recd_pointer = recd_pointer->next_num;
advances the pointer to the next object in the list.
Related References