linkedlist.c - #include <stdio.h> The file stlib.h must be#include'd in order to use malloc#include <stdlib.h> This is a struct declaration for a call

linkedlist.c - #include <stdio.h> The file stlib.h must...

This preview shows page 1 - 2 out of 2 pages.

#include <stdio.h> // The file stlib.h must be #include'd in order to use malloc() #include <stdlib.h> // This is a struct declaration for a call that we can use in a linked list. // It contains a data field holding an int and a next field that points // to the next cell in the list. struct cell { int data; struct cell *next; }; // This function takes an integer parameter n and creates a linked // list of n cells, whose data fields are the numbers from between // 1 and n. It then prints the linked list. Notice that since we // are putting each new cell we create at the beginning (not the end) // of the list, the numbers are in reverse order -- i.e. the first cell // contains n, the second cell contains (n-1), and so on. void build_list(int n) { // The head pointer will always point to the beginning of the list. // Initially it is NULL, i.e. it doesn't point to anything. struct cell *head = NULL; for(int i = 1; i <= n; i++) { // Each time through the loop, we call malloc() to allocate enough // space in memory to hold one cell. malloc() takes as its // parameter, the number of bytes needed. Since we don't necessarily know
Image of page 1
Image of page 2

You've reached the end of your free preview.

Want to read both pages?

  • Fall '12
  • Barrett
  • struct DECLARATION

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture