Thursday, September 25, 2014

Anatomy of a Program That Stores Five Integers Using Linked Lists and Prints Them Out

#include <stdio.h>
#include <stdlib.h> //For malloc function
struct cell
{
    int value;
    struct cell* next;
};
typedef struct cell node;
void addAtBeginning(node*,node*);
int main()
{
    node * head = NULL;    //Signifies the end of the list
 
   
  
    puts("Please specify how many numbers you will enter.");
    int amount = 0;
    int counter = 0;
   
    scanf("%d", &amount); //Enters 5
    for(counter = 0; counter < amount; counter++) //While counter < 5
    {
        puts("Please enter a number.");
        node * temp = NULL; //Creates a temporary node to hold each number
        temp = malloc(sizeof(node)); //Allocates space for each node
        scanf("%d", &(temp->value));// The -> gives us the value and the
                                                       //external & gives us the address of that value
                                                     
        addAtBeginning(head, temp);//Gives the top node and the node to be added
        head = temp; //Makes the new node the top node
    }
    node * temp = head; //Creates a temporary node (so we dont change the
                                      //value  by accident

    while(temp!=NULL) //While we're not at the end of the list:
    {   
        printf("%d", temp->value); //Print the value of the current node
        temp=temp->next;             //moves the iteration through to the next node
    }
   


}
void addAtBeginning(node *atFront, node *nodeToAdd)
{
    nodeToAdd->next=atFront; //Links the NEW top node to the former top node
}